generate a random number between 1 and 100 in rust

To generate a random number between 1 and 100 in Rust, you can use the rand crate. First, add the crate to your Cargo.toml file:

[dependencies]
rand = "0.8.4"
30 chars
3 lines

Then, in your Rust code, you can use the Rng trait from the rand crate to generate a random number:

main.rs
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let random_number = rng.gen_range(1, 101);
    println!("Random number: {}", random_number);
}
165 chars
8 lines

In this code, we first create a random number generator using rand::thread_rng(). This generates a random seed based on the current thread, which gives us a source of entropy for our random number generator.

Next, we use the gen_range() method from the Rng trait to generate a random number between 1 and 100. The gen_range() method generates a random number in the range [start, end), so we pass it 1 and 101.

Finally, we print out the randomly generated number using println!(). With this code, we'll get a different random number every time we run the program!

gistlibby LogSnag