# 生成随机值

## 生成随机数

use rand::Rng;

fn main() {

let n1: u8 = rng.gen();
let n2: u16 = rng.gen();
println!("Random u8: {}", n1);
println!("Random u16: {}", n2);
println!("Random u32: {}", rng.gen::<u32>());
println!("Random i32: {}", rng.gen::<i32>());
println!("Random float: {}", rng.gen::<f64>());
}


## 生成范围内随机数

use rand::Rng;

fn main() {
println!("Integer: {}", rng.gen_range(0..10));
println!("Float: {}", rng.gen_range(0.0..10.0));
}



use rand::distributions::{Distribution, Uniform};

fn main() {
let die = Uniform::from(1..7);

loop {
let throw = die.sample(&mut rng);
println!("Roll the die: {}", throw);
if throw == 6 {
break;
}
}
}


## 生成给定分布随机数

use rand_distr::{Distribution, Normal, NormalError};

fn main() -> Result<(), NormalError> {
let normal = Normal::new(2.0, 3.0)?;
let v = normal.sample(&mut rng);
println!("{} is from a N(2, 9) distribution", v);
Ok(())
}


## 生成自定义类型随机值

use rand::Rng;
use rand::distributions::{Distribution, Standard};

#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}

impl Distribution<Point> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Point {
let (rand_x, rand_y) = rng.gen();
Point {
x: rand_x,
y: rand_y,
}
}
}

fn main() {
let rand_tuple = rng.gen::<(i32, bool, f64)>();
let rand_point: Point = rng.gen();
println!("Random tuple: {:?}", rand_tuple);
println!("Random Point: {:?}", rand_point);
}


## 从一组字母数字字符创建随机密码

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

fn main() {
.sample_iter(&Alphanumeric)
.take(30)
.map(char::from)
.collect();

println!("{}", rand_string);
}


## 从一组用户定义字符创建随机密码

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