create a password with uppercase, lowercase letters, numbers and symbols in rust

To create a password with uppercase, lowercase letters, numbers and symbols in Rust, we can use the rand crate to generate random characters and build the password string. Here's an example function to generate a password with a specified length:

main.rs
extern crate rand;

use rand::{Rng, thread_rng};

const ASCII_CHARS: [char; 94] = ['!', '\"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/',
                                 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>',
                                 '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                                 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\',
                                 ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                                 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                                 '{', '|', '}', '~'];

fn generate_password(length: u32) -> String {
    let mut rng = thread_rng();
    let mut password = String::new();
    let ascii_range = ASCII_CHARS.len();

    for _ in 0..length {
        let random_char = ASCII_CHARS[rng.gen_range(0, ascii_range)];
        password.push(random_char);
    }
    password
}
1066 chars
24 lines

The function generate_password takes a length parameter indicating the desired length of the password. It creates a new thread_rng and uses it to generate a random character for each position in the password string. The function uses an array of the 94 ASCII characters that include uppercase and lowercase letters, numbers, and symbols. The random character is chosen from this array using the gen_range function from the rand crate.

To use this function, call it with the desired password length:

main.rs
let password = generate_password(12);
println!("{}", password); // Prints something like "*3O83{!]<EU}"
104 chars
3 lines

This will generate a password with 12 characters containing a mix of uppercase, lowercase letters, numbers and symbols.

gistlibby LogSnag