2.1.0 What You Will Learn
In this chapter, you will learn:
- Variable declarations
- Related functions
- Enum types
- Advanced use of
println!() - ...
2.1.1 Game Goal
- Generate a random number between 1 and 100
- Prompt the player to enter a guess (covered in this chapter)
- After the guess, the program will tell the player whether the guess is too large or too small
- If the guess is correct, print a celebration message and exit the program
2.1.2 Code Implementation
Step 1: Print the game title and prompt the user
- Build the
mainfunction. How to build a function and its format were mentioned in 1.2. Basic Understanding of Rust and Printing "Hello World", so I will not repeat them here:
fn main() {
}
- Use the
println!()macro to print text:
fn main() {
println!("Number Guessing Game");
println!("Guess a number");
}
Step 2: Create a variable to store the user's input
After prompting the user for input, the program needs a variable to store that input. The code line should look like this:
let mut guess = String::new();
-
letdeclares a new variable, and by default the variable is immutable. - Adding
mutafterletmeans the declared variable is mutable. -
guessis the name of the variable. -
=is used for assignment. -
String::new()is a static method used to create a new, empty string.Stringis the UTF-8 dynamic string type provided by Rust’s standard library.::indicates thatnew()is an associated function of theStringtype, meaning it is implemented for the type itself rather than for a specific string instance, similar to a static method in C# or Java. CallingString::new()returns a newStringinstance with no content, that is, an empty string.
Many types in Rust have a new() function, and new() is a common name for creating instances of a type.
Step 3: Read the user's input
Next we need to read the user’s input. The code is:
io::stdin().read_line(&mut guess).expect("Could not read the line");
-
iois the module name. This module contains thestdin()function we need. -
::is used to access an associated function. -
stdin()is a function that obtains the standard input stream and returns an instance of theStdintype. It is used as a handle to process standard input from the terminal. -
.read_line()is a method provided by theStdintype. It reads a line from standard input into a string and passes it to a mutable string variable.read_line()also returns aResult, an enum with two variants:OkandErr. Ifread_line()succeeds, it returnsOkwith the number of bytes read; if it fails, it returnsErrwith the reason for failure. -
&mut guesspasses the content read by.read_line()into the mutable variableguess. Here,&means taking a reference, which allows the same data (memory address) to be accessed in different parts of the code.mutmeans the referenced variable is mutable. - Errors may occur while reading, so we need to call
.expect(), which is a method on theResulttype returned byread_line(). If reading fails,read_line()returnsErr, and.expect()immediately triggerspanic!, ends the current program, and prints the error message provided toexpect. If reading succeeds,read_line()returnsOk, and.expect()gives back the attached value.
PS: You can omit .expect(), but cargo build will emit a warning.
If you are writing this in an IDE, you may notice that io is highlighted in red. That is because this program has not yet declared that module as a dependency. You only need to add the import at the beginning of the program:
use std::io;
-
useis the keyword for importing items. -
std::iorefers to theiomodule under the standard library (std).
You can also add the library name directly on the line that uses the io module, so you do not need to add an import at the top of the program:
std::io::stdin().read_line(&mut guess).expect("Could not read the line");
In fact, by default Rust imports the contents of a module called prelude into the scope of every program (a concept we will discuss later). Some people call it the prelude module. If the type you want to use is not in the prelude, you need to import it explicitly.
Step 4: Print the user's input
Finally, print the user’s input:
println!("The number you guessed is:{}", guess);
- In
"The number you guessed is:{}",{}is a placeholder whose value will be replaced at output time by the value of the following variable, which isguesshere.
2.1.3 Result
Here is the complete code:
use std::io;
fn main() {
println!("Number Guessing Game");
println!("Guess a number");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Could not read the line");
println!("The number you guessed is:{}", guess);
}
Result:


Top comments (0)