Rust Random Number Generation Generating Two Random Numbers with Rand


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

rand = "0.3"

This will retrieve the rand crate from 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