Rust中如何產生隨機數或密碼?

banq發表於2022-09-21

一個生成隨機數的簡單程式:

use rand::Rng;

fn main() {
  let mut range = rand::thread_rng();
  let num: i32 = range.gen();
  println!("Random: {}", n1);
}


生成隨機字母數字字元來建立密碼生成器:

use rand::Rng;
const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789)(*&^%$#@!";

const LEN: i32 = 25;

fn main() {
  let mut rng = rand::thread_rng();
  let password: String = (0..LEN)
     .map(|_| {
     let idx = rng.gen_range(0..CHARSET.len());
      CHARSET[idx] as char
    })
    .collect();

   println!("Password: {}", password);
}

相關文章