create a password with at least one number in rust

Here is an example code snippet in Rust to generate a random password with at least one number:

main.rs
use rand::{Rng, thread_rng};
use rand::distributions::Alphanumeric;

fn generate_password(length: usize) -> String {
    let mut rng = thread_rng();
    let mut password: String = rng.sample_iter(&Alphanumeric)
        .take(length)
        .map(char::from)
        .collect();
    
    if !password.chars().any(char::is_numeric) {
        // if there is no number in the password, replace a random character with a random number
        let idx = rng.gen_range(0, length);
        password.replace_range(idx..idx+1, rng.gen_range(0..=9).to_string().as_str());
    }

    password
}

fn main() {
    println!("{}", generate_password(10));
}
641 chars
23 lines

Explanation:

  • We use the rand crate to generate random characters for the password.
  • The generate_password function takes a length parameter and generates a string of random characters using Alphanumeric distribution.
  • If the password does not contain any number, we replace a randomly selected character with a randomly generated number.

gistlibby LogSnag