generate a random number between 0 and 1 in rust

To generate a random number between 0 and 1 in Rust, you can use the rand crate's Rng trait.

Here is an example code snippet:

main.rs
use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let random_number: f64 = rng.gen();
    println!("{}", random_number);
}
143 chars
8 lines

In this code, we first import the Rng trait from the rand crate. We then create a new ThreadRng using the thread_rng function. This is a random number generator that is seeded from the operating system's entropy source.

Next, we generate a random number using the gen method, which generates a random number of the given type. In this case, we specify that we want a f64 (a floating-point number).

Finally, we print out the random number using println!.

related categories

gistlibby LogSnag