create a password with a custom length, uppercase letters and lowercase letters in rust

We can create a password with custom length and with a combination of uppercase and lowercase letters using Rust's rand crate. Here is an example code that generates a password of length n:

main.rs
use rand::Rng;

fn generate_password(n: usize) -> String {
    let mut rng = rand::thread_rng();
    let password: String = (0..n)
        .map(|_| {
            let random_ascii = rng.gen_range(65..91) as u8;         // generates random uppercase letters
            let random_ascii2 = rng.gen_range(97..123) as u8;       // generates random lowercase letters
            let choice = rng.gen_range(0..2);                        // randomly chooses between uppercase and lowercase
            if choice == 0 {
                random_ascii as char
            } else {
                random_ascii2 as char
            }
        })
        .collect();
    password
}

fn main() {
    let password = generate_password(10);
    println!("{}", password);   // prints a password of length 10 with a combination of uppercase and lowercase letters
}
845 chars
24 lines

The example code uses the rand::thread_rng() function to get a random number generator with a default seed from the current thread of execution. Then, for each character of the password, it generates a random ASCII code for an uppercase letter and a lowercase letter and randomly chooses between the two. Finally, it collects the characters into a String and returns the password.

gistlibby LogSnag