How do I create a random String by sampling from alphanumeric characters?

As explained in the rand 0.5.0 docs, gen_ascii_chars is deprecated and you should use sample_iter(&Alphanumeric) instead.

use rand::{distributions::Alphanumeric, Rng}; // 0.8

fn main() {
    let s: String = rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(7)
        .map(char::from)
        .collect();
    println!("{}", s);
}

Leave a Comment