Random Numbers in Rust

Here’s the translation of the Go code to Rust, with explanations in Markdown format suitable for Hugo:

Rust’s rand crate provides pseudorandom number generation.

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();

    // For example, `gen_range` returns a random integer n,
    // where 0 <= n < 100.
    print!("{},", rng.gen_range(0..100));
    println!("{}", rng.gen_range(0..100));

    // `gen` returns a random f64 f,
    // where 0.0 <= f < 1.0.
    println!("{}", rng.gen::<f64>());

    // This can be used to generate random floats in
    // other ranges, for example 5.0 <= f' < 10.0.
    print!("{},", rng.gen::<f64>() * 5.0 + 5.0);
    println!("{}", rng.gen::<f64>() * 5.0 + 5.0);

    // If you want a known seed, create a new
    // `StdRng` with a specific seed.
    let mut rng = rand::rngs::StdRng::seed_from_u64(42);
    print!("{},", rng.gen_range(0..100));
    println!("{}", rng.gen_range(0..100));

    // Creating another RNG with the same seed will
    // produce the same sequence of random numbers.
    let mut rng = rand::rngs::StdRng::seed_from_u64(42);
    print!("{},", rng.gen_range(0..100));
    println!("{}", rng.gen_range(0..100));
}

To run this program, you’ll need to add the rand crate to your Cargo.toml file:

[dependencies]
rand = "0.8.5"

Then you can run the program using Cargo:

$ cargo run
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Some of the generated numbers may be different when you run the sample.

See the rand crate documentation for references on other random quantities that Rust can provide.