rust random number in range
To generate a random number within a specific range in Rust, you can use the rand
crate. Here's an example code snippet that demonstrates how to generate a random number between a given minimum and maximum value:
use rand::Rng;
fn main() {
let min = 1;
let max = 10;
let mut rng = rand::thread_rng();
let random_number = rng.gen_range(min..=max);
println!("Random number: {}", random_number);
}
In this code, we first import the Rng
trait from the rand
crate. Then, we define the minimum and maximum values for the range. Next, we create a random number generator using rand::thread_rng()
. Finally, we generate a random number within the specified range using the gen_range
method.
Please make sure to add the rand
crate to your Cargo.toml
file in order to use it in your Rust project.
I hope this helps! Let me know if you have any further questions.