[[email protected] test]# cargo new guessing_game
Created binary (application) `guessing_game` package
[[email protected] test]# cd guessing_game
[[email protected] guessing_game]# ls
Cargo.toml src
[[email protected] guessing_game]# cat Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
authors = ["tanpf <[email protected]>"]
edition = "2018"
[dependencies]
themain function is the entry point into the program
# vim src/main.rs
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
println! is a macro that prints a string to the screen, then create a place to store the user input
Notice that this is alet statement, which is used to create avariable. In Rust, variables are immutable by default. The following example shows how to usemut before the variable name to make a variable mutable:
let foo = 5; // immutable
let mut bar = 5; // mutable
You now know thatlet mut guess will introduce a mutable variable namedguess. On the other side of the equal sign (=) is the value thatguess is bound to, which is the result of callingString::new, a function that returns a new instance of aString.String is a string type provided by the standard library that is a growable, UTF-8 encoded bit of text.
The:: syntax in the::new line indicates thatnew is anassociated function of theString type. An associated function is implemented on a type, in this caseString, rather than on a particular instance of aString. Some languages call this astatic method.
Thisnew function creates a new, empty string. You’ll find anew function on many types, because it’s a common name for a function that makes a new value of some kind.
To summarize, thelet mut guess = String::new(); line has created a mutable variable that is currently bound to a new, empty instance of aString
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
If we hadn’t listed the use std::io line at the beginning of the program, we could have written this function call as std::io::stdin. The stdin function returns an instance of std::io::Stdin, which is a type that represents a handle to the standard input for your terminal.
The next part of the code, .read_line(&mut guess), calls the read_line method on the standard input handle to get input from the user. We’re also passing one argument to read_line: &mut guess.
The & indicates that this argument is a reference, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times. References are a complex feature, and one of Rust’s major advantages is how safe and easy it is to use references. You don’t need to know a lot of those details to finish this program. For now, all you need to know is that like variables, references are immutable by default. Hence, you need to write &mut guess rather than &guessto make it mutable.
.expect("Failed to read line");
As mentioned earlier, read_line puts what the user types into the string we’re passing it, but it also returns a value—in this case, an io::Result. Rust has a number of types named Result in its standard library: a generic Result as well as specific versions for submodules, such as io::Result.
The Result types are enumerations, often referred to as enums. An enumeration is a type that can have a fixed set of values, and those values are called the enum’s variants.
An instance of io::Result has an expectmethod that you can call. If this instance of io::Result is an Err value, expect will cause the program to crash and display the message that you passed as an argument to expect. If the read_line method returns an Err, it would likely be the result of an error coming from the underlying operating system. If this instance of io::Result is an Ok value, expect will take the return value that Ok is holding and return just that value to you so you can use it. In this case, that value is the number of bytes in what the user entered into standard input.
If you don’t call expect, the program will compile, but you’ll get a warning.
println!("You guessed: {}", guess);
let x = 5;
let y = 10;
println!("x = {} and y = {}", x, y);