Random number
- Rust course
- Beginner
- Lesson 63/115
- 6 min
Generate a secret number with the rand crate.
A random number
Rust's standard library has no random number generator; the rand crate is used for that. The dependency is added to Cargo.toml and cargo build downloads it:
[dependencies]
rand = "0.8"use rand::Rng;
let gizli = rand::thread_rng().gen_range(1..=100);The gen_range method comes from the Rng trait; it can't be called until the trait is brought into scope (use rand::Rng;).
Without a crate: a simple generator
Since external crates can't be downloaded in the exercise environment, we can write a simple linear congruential generator (LCG) for learning purposes. The same seed always gives the same sequence, which makes testing easy:
let mut tohum: u64 = 42;
tohum = (tohum * 1103515245 + 12345) % 2147483648;
let gizli = tohum % 100 + 1; // 1..=100This method is not suitable for security; use rand in real programs.
Practice Generate the secret
Start with let mut tohum: u64 = 42;. Apply tohum = (tohum * 1103515245 + 12345) % 2147483648; once, then compute the secret with tohum % 100 + 1 and print it as Gizli sayı: ....
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut tohum: u64 = 42;
tohum = (tohum * 1103515245 + 12345) % 2147483648;
let gizli = tohum % 100 + 1;
println!("Gizli sayı: {}", gizli);
}Expected output
Gizli sayı: 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which values can <code>gen_range(1..=100)</code> produce?
- 0 to 99
- 1 to 99
- Any u32
- 1 to 100, both included Correct answer
Explanation: ..= is an inclusive range; 100 is included too.
2 Bring the trait into scope
use rand::____;
let gizli = rand::thread_rng().gen_range(1..=100);
use rand::Rng;
let gizli = rand::thread_rng().gen_range(1..=100);
Explanation: gen_range is a method of the Rng trait.
3 Piece and meaning
| Term | Meaning |
|---|---|
rand = "0.8" |
Dependency |
thread_rng() |
Generator |
gen_range(1..=100) |
Between 1 and 100 |
% 100 + 1 |
Reduces to the range |