小白学Rust(一):Rust产生随机数

先按本人教程如何利用科大源提速Cargo和Rust做好相关配置。然后在linux Bash下执行:

cargo new random --bin

这会在当前目录创建一个random文件夹,然后修改src下面的main.rs,代码如下:

extern crate rand;

use rand::Rng;

fn main(){
  let mut rng =rand::thread_rng();
  // Each thread has an automatically-initialised random number generator:

  // Integers are uniformly distributed over the type's whole range:

  let n1:u8 = rng.gen();
  let n2:u16 = rng.gen();
  println!("n1 is :{}",n1);
  println!("n2 is :{}",n2);
  println!("here is a random u32 number:{}",rng.gen::<u32>());
  println!("here is a random i32 number:{}",rng.gen::<i32>());

  // Floating point numbers are uniformly distributed in the half-open range [0, 1)
  println!("Random float: {}", rng.gen::<f64>());


  //Generates a random value within half-open [0, 10) range (not including 10) with Rng::gen_range.
  println!("Integer: {}", rng.gen_range(0, 10));
  println!("Float: {}", rng.gen_range(0.0, 10.0));



}

然后在Cargo.toml最后一行加入:

rand = "0.3.17"

执行cargo build和cargo run之后可以看到打印:

warning: custom registry support via the `registry.index` configuration is being removed, this functionality will not work in the future
   Compiling random v0.1.0 (file:///home/rustcode/basic/random)
    Finished dev [unoptimized + debuginfo] target(s) in 0.43 secs
     Running `target/debug/random`
n1 is :209
n2 is :28903
here is a random u32 number:867979277
here is a random i32 number:-2005811675
Random float: 0.0010826636175251814
Integer: 2
Float: 2.113870312229329

当然,这里用户可以自定义一个随机数生成方式,比如想要随机生成一个点的坐标:

extern crate rand;

use rand::{Rng,Rand};

#[derive(Debug)]
struct Point{
  x:i32,
  y:i32,
}
impl Rand for Point{
  fn rand<R:Rng>(rng:&mut R) -> Point{
  let (rand_x,rand_y) = rng.gen();
  Point{
  x:rand_x,
  y:rand_y,
    }


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


}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值