2.1.0. Key Points in This Article
In this article, you will learn:
- Variable declaration
- Related functions
- Enumeration types
- Advanced usage of
println!() - ...
2.1.1. Game Objectives
- Generate a random number between 1 and 100
- Prompt the player to input a guess (covered in this article)
- After guessing, the program will indicate whether the guess is too high or too low
- If the guess is correct, print a congratulatory message and exit the program
2.1.2. Code Implementation
Step 1: Print the game name and prompt user input
- Build the main function. How to build functions and their format was covered in 1.2. Basic Understanding of Rust and Printing "Hello World", so it won't be repeated here:
fn main(){
}
- Use the
println!()macro function to print text:
fn main{
println!("猜数游戏 Number Guessing Game");
println!("猜一个数 Guess a number");
}
Step 2: Create a variable to store user input
After prompting the user for input, the program needs a variable to store the user's input. This line of code should be:
let mut guess = String::new();
letis used to declare a new variable, but by default it's an immutable variable.Adding
mutafterletmeans declaring this variable as a mutable variable.guessis the name of this variable=is used for assignmentString::new()is a static method used to create a new, empty string.Stringis a dynamic string type (UTF-8 encoded) provided by Rust's standard library.::indicates thatnew()is an associated function of theStringtype. Associated functions are implemented for the type itself, not for a specific instance of the string, similar to static methods in C# or Java. CallingString::new()returns a newStringinstance with no content (empty string).
Many types in Rust have a new() function. new() is a conventional name for creating type instances.
Step 3: Get user input
Next, we need to read the user's input. This part of the code is:
io::stdin().read_line(&mut guess).expect("无法读取行 Could not read the line");
iois a module name. This module contains the functionstdin()that we need.::is used to access associated functionsstdin()is a function that gets the standard input stream, returning an instance of theStdintype, which is used as a handle to process standard input from the terminal..read_line()is a method provided by theStdintype, used to read a line of content from standard input and put it into a string, passing it to a mutable string type variable.read_line()also has a return value of typeResult, an enumeration type with two values:OkandErr. Ifread_line()can successfully read, this enumeration type will returnOkand the read content; if it cannot read, it will returnErrand the reason for the read failure.&mut guessmeans passing the content read by.read_line()into this mutable variableguess. The&here is an address operator, indicating that this parameter is a reference. Through references, you can access the same data (memory address) in different parts of the code.mutindicates that what's being passed is a mutable variable.Errors may occur during reading, so we need to call
.expect(), which is a method of theResulttype (same type as the return value ofread_line()). If reading fails, as mentioned above,read_line()will returnErr, and.expect()will directly triggerpanic!to terminate the current program and print the error message inexpect. Conversely, ifread_line()returnsOk,.expect()will return the attached value to the user.
PS: You can also not write .expect(), but it will generate a warning during build
If you're writing in an IDE up to this point, you'll notice that io is highlighted in red. This is because the program hasn't declared the use of this module yet. Just declare the reference at the beginning of the program:
use std::io;
-
useis the keyword for declaring references -
std::iorefers to theiomodule under the standard library (std)
You can also directly add the library name before the line that calls the io module, so you don't need to declare the reference at the beginning 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 every program's scope (this concept will be covered later). Some people call it the prelude module. If the type you want to use is not in prelude, you need to declare the reference.
Step 4: Print the user's input
Finally, print the user's input. This part of the code is:
println!("你猜测的数是The number you guessed is:{}",guess);
- The
{}in"你猜测的数是The number you guessed is:{}"is a placeholder, whose value will be replaced with the value of the variable behind it (here it's theguessvariable) during output.
2.1.3. Code Effect
This 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);
}
Effect:


Top comments (0)