// First we create our corpus, or set of characters that will go in our password const PASSWORD_CHARS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // Import the random generator and the interator random extension trait :dep rand extern crate rand; use rand::{seq::IteratorRandom, thread_rng, Rng}; // Then we create our password generator fn gen_passwd(len: u16, rng: &mut impl Rng) -> String { // The password buffer let mut password = String::new(); // Loop trough 0 up to our password length for _ in 0..len { // Add a character password.push( PASSWORD_CHARS // Out of our password character list .chars() // As an iterator over the characters .choose(rng) // This choose method comes form the `rand::seq::IteratorRandom` import .expect("Empty iterator for password chars"), // Expect won't fail unless our corpus was empty ); } password } // To use our function we have to first create a random generator let mut rng = thread_rng(); // Then we can generate random numbers! gen_passwd(32, &mut rng) gen_passwd(12, &mut rng) gen_passwd(124, &mut rng)