Movatterモバイル変換


[0]ホーム

URL:


Rust Cookbook

    Generate Random Values

    Generate random numbers

    rand-badgecat-science-badge

    Generates random numbers with help of random-numbergeneratorrand::Rng obtained viarand::rng. Each thread has aninitialized generator. Integers are uniformly distributed over the range of thetype, and floating point numbers are uniformly distributed from 0 up to but notincluding 1.

    use rand::Rng;fn main() {    let mut rng = rand::thread_rng();    let random_number: u32 = rng.gen();    println!("Random number: {}", random_number);}

    Generate random numbers within a range

    rand-badgecat-science-badge

    Generates a random value within half-open[0, 10) range (not including10) with [Rng::gen_range].

    use rand::Rng;fn main() {    let mut rng = rand::rng();    println!("Integer: {}", rng.gen_range(0..10));    println!("Float: {}", rng.gen_range(0.0..10.0));}

    [Uniform] can obtain values withuniform distribution.This has the same effect, but may be faster when repeatedly generating numbersin the same range.

    use rand::Rng;use rand_distr::{Distribution, Uniform};fn main() {    let mut rng = rand::rng();    let die = Uniform::new_inclusive(1, 6)        .expect("Failed to create uniform distribution: invalid range");    loop {        let throw = die.sample(&mut rng);        println!("Roll the die: {}", throw);        if throw == 6 {            break;        }    }}

    Generate random numbers with given distribution

    rand_distr-badgecat-science-badge

    By default, random numbers in therand crate haveuniform distribution. Therand_distr crate providesother kinds of distributions. To use them, you instantiatea distribution, then sample from that distribution usingDistribution::sample with help of a random-numbergeneratorrand::Rng.

    Thedistributions available are documented here.An example using theNormal distribution is shown below.

    use rand::Rng;use rand_distr::{Distribution, LogNormal, Normal};fn main() {    let mut rng = rand::rng();    let normal = Normal::new(2.0, 3.0)        .expect("Failed to create normal distribution");    let log_normal = LogNormal::new(1.0, 0.5)        .expect("Failed to create log-normal distribution");    let v = normal.sample(&mut rng);    println!("{} is from a N(2, 9) distribution", v);    let v = log_normal.sample(&mut rng);    println!("{} is from an ln N(1, 0.25) distribution", v);}

    Generate random values of a custom type

    rand-badgecat-science-badge

    Randomly generates a tuple(i32, bool, f64) and variable of user defined typePoint.Implements the [Distribution] trait on type Point for [Standard] in order to allow random generation.

    use rand::Rng;#[derive(Debug)]struct Point {    x: i32,    y: i32,}impl Point {    fn random<R: Rng>(rng: &mut R) -> Self {        Point {            x: rng.random(),            y: rng.random(),        }    }}fn main() {    let mut rng = rand::rng();    let rand_tuple = rng.random::<(i32, bool, f64)>();    let rand_point = Point::random(&mut rng);    println!("Random tuple: {:?}", rand_tuple);    println!("Random Point: {:?}", rand_point);}

    Create random passwords from a set of alphanumeric characters

    rand-badgecat-os-badge

    Randomly generates a string of given length ASCII characters in the rangeA-Z, a-z, 0-9, withAlphanumeric sample.

    use rand::Rng;fn main() {    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\                            abcdefghijklmnopqrstuvwxyz\                            0123456789";    const PASSWORD_LEN: usize = 30;    let mut rng = rand::rng();    let password: String = (0..PASSWORD_LEN)        .map(|_| {            let idx = rng.random_range(0..CHARSET.len());            CHARSET[idx] as char        })        .collect();    println!("{}", password);}

    Create random passwords from a set of user-defined characters

    rand-badgecat-os-badge

    Randomly generates a string of given length ASCII characters with customuser-defined bytestring, withgen_range.

    use rand::Rng;const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\                        abcdefghijklmnopqrstuvwxyz\                        0123456789)(*&^%$#@!~";const PASSWORD_LEN: usize = 30;fn main() {    let mut rng = rand::rng();    let password: String = (0..PASSWORD_LEN)        .map(|_| {            let idx = rng.gen_range(0..CHARSET.len());            char::from(CHARSET[idx])        })        .collect();    println!("{:?}", password);}

    [8]ページ先頭

    ©2009-2025 Movatter.jp