Rust program to generate a random password


Generate a random password

Rust Programming Language


Generate a random password


Problem


In this program, we will generate a random password and print generated password on the console screen.

Add random external library to your project

Create your project using the below command.
$cargo new random --bin{codeBox}

Goto the project folder cd random and edit Cargo.toml file.
$random>nano Cargo.toml{codeBox}

Then add dependency in Cargo.toml file
[dependencies]
rand = "0.5.5"{codeBox}

After that, build your project using the below command
$random>cargo build{codeBox}

Then execute your project after modification in the src/main.rs source file.
$random>cargo run{codeBox}


Input


// Rust program to generate a 
// random password

use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;

fn main() {
    let password: String = thread_rng()
        .sample_iter(&Alphanumeric)
        .take(10)
        .map(char::from)
        .collect();
        
    println!("Generated password: {}", password);
}{codeBox}


Output


$random> cargo run
Compiling random v0.1.0 (/home/arvind/Desktop/rust/random)
    Finished dev [unoptimized + debuginfo] target(s) in 0.33s
     Running `target/debug/random`

Generated password: AUg2u0JJNx{codeBox}


Explanation


In the above program, we imported the "rand" library to our project for generating random numbers. We imported the "rand" library using the below line:

use rand::Rng;{codeBox}

In the main() function, we generated a random password using rand library functions and printed the result.

Post a Comment