loading...

Day39:Generate random value - 100DayOfRust

0xbf profile image Bo ・1 min read

We can use external crate rand to generate random value.

In Cargo.toml:

rand="0.7.3"

In main.rs:

use rand::{prelude::*, Rng, distributions::Alphanumeric};
// Rng stands for "random number generator"

fn main() {
    let num: u32 = rand::random();
    println!("generated rand integer: {}", num);

    let c: char = rand::random();
    println!("generated rand char: {}", c);

    let mut rng = rand::thread_rng();
    // gen function is a generic-type function
    let b1: bool = rng.gen();
    println!("generated boolean is {}", b1);

    let n1: u32 = rng.gen();
    println!("generated integer is {}", n1);

    let f1: f32 = rng.gen();
    println!("generated float is {}", f1);

    // generate number within range
    let range_num = rng.gen_range(0, 10);
    println!("number b/t 0-10 is {}", range_num);

    let range_decimal = rng.gen_range(0.0, 1.0);
    println!("number b/t 0-1 is {}", range_decimal);

    // generate a string with specified length
    let rand_str: String = rng.sample_iter(&Alphanumeric).take(15).collect();
    println!("generated random string: {}", rand_str);

    // shuffle some array
    let mut nums: Vec<i32> = (1..10).collect();
    // .shuffle need rand::prelude::*
    nums.shuffle(&mut rng);
    println!("num list: {:?}", nums);
}

Run it cargo run:

generated rand integer: 2802536511
generated rand char: 񭌀
generated boolean is true
generated integer is 497331788
generated float is 0.0054394007
number b/t 0-10 is 3
number b/t 0-1 is 0.23074173856274816
generated random string: 97lbEyO3SVJgt7k
num list: [8, 1, 2, 3, 5, 4, 9, 6, 7]

Reference:

Discussion

pic
Editor guide