create a password with uppercase letters and lowercase letters in rust

To create a password with uppercase and lowercase letters in Rust, you can use the Rust standard library's rand crate to generate random numbers, and then use the char::from_u32 function to convert those numbers to letters.

Here's an example function that generates a password of a specified length:

main.rs
use rand::Rng;

fn generate_password(length: usize) -> String {
    let mut password = String::new();
    let mut rng = rand::thread_rng();

    for _ in 0..length {
        let rand_num = rng.gen_range(0, 2);
        let new_char = match rand_num {
            0 => rng.gen_range(b'A', b'Z' + 1) as char, // uppercase letter
            _ => rng.gen_range(b'a', b'z' + 1) as char, // lowercase letter
        };
        password.push(new_char);
    }

    password
}
468 chars
18 lines

This function creates an empty String, creates a source of randomness, and then loops length times. Each loop generates a random number between 0 and 1, and uses a match expression to decide whether to add an uppercase or lowercase letter to the password. The char values are generated using the gen_range method on the source of randomness, and then converted to chars using as char. Finally, the String is returned.

You can call this function with a desired password length to generate a password:

main.rs
fn main() {
    let password = generate_password(10);
    println!("Generated password: {}", password);
}
106 chars
5 lines

This will output a 10-character password consisting of uppercase and lowercase letters.

gistlibby LogSnag