DEV Community

Cover image for [Rust Guide] 2.1. Number Guessing Game Pt.1 - One Guess
SomeB1oody
SomeB1oody

Posted on

[Rust Guide] 2.1. Number Guessing Game Pt.1 - One Guess

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(){

}  
Enter fullscreen mode Exit fullscreen mode
  • Use the println!() macro function to print text:
fn main{
    println!("猜数游戏 Number Guessing Game");

    println!("猜一个数 Guess a number");
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode
  • let is used to declare a new variable, but by default it's an immutable variable.

  • Adding mut after let means declaring this variable as a mutable variable.

  • guess is the name of this variable

  • = is used for assignment

  • String::new() is a static method used to create a new, empty string. String is a dynamic string type (UTF-8 encoded) provided by Rust's standard library. :: indicates that new() is an associated function of the String type. Associated functions are implemented for the type itself, not for a specific instance of the string, similar to static methods in C# or Java. Calling String::new() returns a new String instance 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");
Enter fullscreen mode Exit fullscreen mode
  • io is a module name. This module contains the function stdin() that we need.

  • :: is used to access associated functions

  • stdin() is a function that gets the standard input stream, returning an instance of the Stdin type, which is used as a handle to process standard input from the terminal.

  • .read_line() is a method provided by the Stdin type, 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 type Result, an enumeration type with two values: Ok and Err. If read_line() can successfully read, this enumeration type will return Ok and the read content; if it cannot read, it will return Err and the reason for the read failure.

  • &mut guess means passing the content read by .read_line() into this mutable variable guess. 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. mut indicates 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 the Result type (same type as the return value of read_line()). If reading fails, as mentioned above, read_line() will return Err, and .expect() will directly trigger panic! to terminate the current program and print the error message in expect. Conversely, if read_line() returns Ok, .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;
Enter fullscreen mode Exit fullscreen mode
  • use is the keyword for declaring references
  • std::io refers to the io module 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");
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
  • 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 the guess variable) 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);  
}
Enter fullscreen mode Exit fullscreen mode

Effect:

Top comments (0)