Random Number Generator in Rust
To generate a random number in Rust, you typically use the rand crate, which is a popular choice for random number generation. First, ensure you have the rand crate included in your Cargo.toml file:
// cargo.toml
[dependencies]
rand = "0.8.4"
// the code:
use rand::Rng; // Rng trait defines methods for random number generation
fn main() {
let mut rng = rand::thread_rng(); // Get a random number generator
let random_number: i32 = rng.gen_range(1..=10); // Generate a random number between 1 and 10, inclusive
println!("Random number: {}", random_number);
}
In this example:
- rand::Rng trait is imported, which provides the gen_range method.
- rand::thread_rng() provides a random number generator local to the current thread of execution and seeded by the operating system.
- gen_range(1..=10) generates a random integer in the range [1, 10], including both endpoints.
- Make sure to add the rand crate to your Cargo.toml to use it in your project.