2.2.0. Key Points in This Article
In this article, you will learn:
- Searching and downloading external Crates
- Cargo dependency management
- Upgrade rules based on semantic versioning
-
randrandom number generator - ...
2.2.1. Game Objectives
- Generate a random number between 1 and 100 (covered in this article)
- Prompt the player to input a guess
- 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.2.2. Code Implementation
Step 1: Finding External Libraries
Although Rust's standard library doesn't provide functions related to generating random numbers, the Rust team has developed external libraries with this functionality. You can find this external library by searching for rand on the official Rust crates management platform (the official package management platform and ecosystem for the Rust programming language). This webpage provides very detailed information about this library.
Rust crates are divided into two types:
Library Crate: A library crate is a library that provides functionality and logical modules, has no
mainfunction, and cannot run independently. It's typically used to share functionality with other code, and its purpose is to provide reusable functional modules. Therandcrate belongs to library crates.Binary Crate: A binary crate is an executable program that contains a
mainfunction and generates a runnable binary file after compilation. Its purpose is to build independent, runnable Rust applications.
Step 2: Adding This External Crate to Cargo Dependencies
Next, we need to add this external library to Cargo dependencies (an introduction to Cargo was covered in the 1.3. Rust Cargo article and won't be repeated here) for the program to call.
Open the Cargo.toml file in the project and add dependencies under dependencies in the format dependency_name = "dependency_version" (this line's syntax is shown in the Install section in the upper right corner of the Crates webpage). This program needs the rand dependency and uses version 0.8.5, so it should be written as rand = "0.8.5". If this dependency has other dependencies, Cargo will automatically download them during compilation.
Actually, the version number format 0.8.5 is a shorthand; its complete form is ^0.8.5, meaning any version compatible with the public API of version 0.8.5 is acceptable. For example, if a dependency's version is 1.2, it means allowing upgrades to any version above 1.2.0, but not upgrading to 2.0.0 or higher versions.
Cargo will continue to use the dependency version you specify until you manually specify another version.
What happens after rebuilding if a project's dependency update would break code based on the old version dependency? The answer lies in the Cargo.lock file. During build, Cargo checks whether a Cargo.lock file has been generated. If it exists, it uses the versions specified in this file, thus avoiding compatibility issues.
If you want to update versions under current standards, just use the cargo update command in the console. Specific steps are:
- Copy the folder path where the Cargo project is located, open terminal, enter command
cd Cargo_project_path - Enter command
cargo update
This command ignores cargo.lock and finds the latest version dependencies that meet the requirements in Cargo.toml through the updated registry, but the version written in Cargo.toml won't change. For example, if a dependency declared in Cargo.toml has version 1.2, it can be upgraded to the latest 1.x.x version through cargo update, but won't upgrade to 2.0.0 or higher versions, and the dependency version written in Cargo.toml will still be 1.2.
Step 3: Using This Dependency in Code
At the beginning of the program, you need to use the keyword use to reference the dependency:
use rand::Rng
rand::Rng is a trait. A trait is similar to interfaces in other languages (like Java interfaces or C++ pure virtual base classes), used to specify a set of functions and methods that types must implement. rand::Rng defines some methods needed by random number generators.
Next, use this trait in the main function to generate random numbers. The specific code is:
let range_number = rand::thread_rng().gen_range(1..101);
PS: For older versions, it should be written as gen_range(1,101)
-
let range_number: Declares an immutable variable calledrange_number -
=: Assignment -
rand::thread_rng: Returns theThreadRngtype, which is a random number generator. This random number generator is located in local thread space and obtains the seed for this random number through the operating system. -
.gen_range(1..101): A method onrand::thread_rngthat takes two parameters: minimum and maximum values. Here it's 1 and 101, so it generates random numbers between 1 and 101, where this range includes 1 but excludes 101.
Finally, print this random number (the usage of println! was introduced in the previous article and won't be elaborated here):
println!("神秘数字是 The secret number is: {}", range_number);
2.2.3. Code Effect
This is the complete code:
use std::io;
use rand::Rng;
fn main() {
let range_number = rand::thread_rng().gen_range(1..101);
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);
println!("神秘数字是 The secret number is: {}", range_number);
}
The running effect is as follows:


Top comments (0)