create a password with a custom length and numbers in rust

You can create a random password in Rust with a custom length and numbers by using Rust's rand crate.

Here's a code snippet that generates a random password with a custom length n and numbers:

main.rs
use rand::Rng;

fn generate_password(n: usize) -> String {
    let chars: Vec<char> = (0..10).map(|i| char::from_digit(i, 10).unwrap()).collect();
    let mut rng = rand::thread_rng();
    let password: String = (0..n)
        .map(|_| chars[rng.gen_range(0..chars.len())])
        .collect();
    password
}

fn main() {
    let password_length = 8;
    let password = generate_password(password_length);
    println!("Random Password: {}", password);
}
455 chars
17 lines

In the above code, we first create a vector chars containing all the digits from 0 to 9 using char::from_digit method. Then we generate a random password of length n by selecting a random digit from the chars vector n times using the gen_range method from the rand crate.

You can change the value of password_length to any desired length and the generate_password function will return a randomly generated password of that length.

gistlibby LogSnag