liveBook · Manning

Rand

As explained in Learn Rust in a Month of Lunches

rand is a Rust crate that provides random-number generation facilities and related randomization utilities.

rand is a Rust crate for generating random numbers and adding practical randomization to programs. Because random numbers are not in Rust’s standard library, rand is commonly added as an external dependency. section 16.5 section 16.5.1

Use rand through Cargo and a small set of familiar functions:

  • Add rand under [dependencies] in Cargo.toml, or run cargo add rand. section 16.5.1
  • Call random::<u16>() for a randomly generated value of a chosen type. section 16.5.2
  • Create a generator with thread_rng() and use gen_range(1..11) for values from 1 through 10. section 16.5.2

Rolling character statistics

A character creator can roll a six-sided die three times for each statistic, or roll four times and discard the lowest result. The resulting totals range from 3 to 18, while the second method usually avoids very low scores. section 16.5.3

[package]
name = "rust_book"
version = "0.1.0"
authors = ["David MacLeod"]
edition = "2021"
 
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
[dependencies]
rand = "0.8.5"

Use this Cargo.toml listing to see where rand belongs and how version 0.8.5 is declared. section 16.5.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains dependency setup, typed generation, bounded ranges, and a dice-rolling application without examining random-number internals.
Examples
Uses typed u16 values, bounded integers from 1 through 10, and role-playing character statistics generated from dice.
What it assumes
Assumes basic Rust project and Cargo familiarity while teaching external-crate installation and random-number APIs directly.
What you can do after
Build programs that add rand through Cargo, generate typed or bounded random values, and create dice-based character statistics.
How it connects
Connects random-number generation with Cargo, the standard library, structs, enums, and external crates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.