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:
30 chars3 lines
Then, in your Rust code, you can use the Rng
trait from the rand
crate to generate a random number:
main.rs165 chars8 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