Rust中如何产生随机数或密码?

22-09-21 banq

一个生成随机数的简单程序:

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);
}