Rust Random Number Generation Generating Two Random Numbers with Rand

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Firstly, you'll need to add the crate into your Cargo.toml file as a dependency.

[dependencies]
rand = "0.3"

This will retrieve the rand crate from crates.io. Next, add this to your crate root.

extern crate rand;

As this example is going to provide a simple output through the terminal, we'll create a main function and print two randomly generated numbers to the console. The thread local random number generator will be cached in this example. When generating multiple values, this can often prove more efficient.

use rand::Rng;

fn main() {
    
    let mut rng = rand::thread_rng();
    
    if rng.gen() { // random bool
        println!("i32: {}, u32: {}", rng.gen::<i32>(), rng.gen::<u32>())
    }
}

When you run this example, you should see the following response in the console.

$ cargo run
     Running `target/debug/so`
i32: 1568599182, u32: 2222135793


Got any Rust Question?