3.1 入门

原文链接: https://rust-random.github.io/book/guide-start.html

如果尚未安装,请先安装 Rust。

接下来,创建一个新 crate 并将 rand 添加为依赖:

1
2
3
cargo new randomly
cd randomly
cargo add rand 

现在,将以下内容粘贴到 src/main.rs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
use rand::prelude::*;

fn main() {
    let mut rng = rand::rng();

    println!("Random die roll: {}", rng.random_range(1..=6));
    println!("Random UUID: 0x{:X}", rng.random::<u128>());

    if rng.random() {
        println!("You got lucky!");
    }
}

运行起来:

1
2
3
4
5
6
7
$ cargo run
   Compiling [..]
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.99s
     Running `target/debug/randomly`
Random die roll: 4
Random UUID: 0xEC3936A465339F8295EE11AB853CCDBF
You got lucky!

其他 crate

本指南还会用到一些其他 crate。需要时,可以编辑 Cargo.toml 的 [dependencies] 部分,或使用 cargo add:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$ cargo add rand_distr
    Updating crates.io index
      Adding rand_distr v0.4.3 to dependencies
             Features:
             + alloc
             + std
             - serde
             - serde1
             - std_math
    Updating crates.io index
最后修改 August 23, 2026: 更新 (499855b16)