From d470d84612ef56031baba1e4016ee9899b0a0884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Malaty=C5=84ski?= Date: Wed, 8 Feb 2023 21:39:45 +0100 Subject: [PATCH] Rand: update to work with latest rand version --- src/rand.md | 22 +++++----------------- 1 file changed, 5 insertions(+), 17 deletions(-) diff --git a/src/rand.md b/src/rand.md index 59c8c0a..0e0c1ee 100644 --- a/src/rand.md +++ b/src/rand.md @@ -7,7 +7,7 @@ To use the `rand` crate, just do the following in your `Cargo.toml` file. ``` [dependencies] -rand = "0.7.3" +rand = "0.8.5" ``` ## Get a random number @@ -15,8 +15,6 @@ rand = "0.7.3" To get a random number, you can simply do the following. ```rust,editable -# extern crate rand; - fn main() { let i: i32 = rand::random(); println!("The random i32 is {}", i); @@ -26,8 +24,6 @@ fn main() { The `random()` is smart enough to know the primitive type it is **supposed** to generate. Check out the example below. ```rust,editable -# extern crate rand; - fn main() { let x: u8 = rand::random(); println!("The random u8 is {}", x); @@ -44,16 +40,14 @@ What about generating a random number within a range? For that, you need to create a random number generator and call its `gen_range()` function. ```rust,editable -# extern crate rand; - use rand::thread_rng; use rand::Rng; fn main() { let mut rng = thread_rng(); - let y: f64 = rng.gen_range(-10.0, 10.0); + let y: f64 = rng.gen_range(-10.0..=10.0); println!("Number from -10. to 10.: {}", y); - println!("Number from 0 to 9: {}", rng.gen_range(0, 10)); + println!("Number from 0 to 9: {}", rng.gen_range(0..10)); } ``` @@ -65,15 +59,13 @@ a new random number generator. It is faster to create the generator once and call its `gen()` function repeatedly. ```rust,editable -# extern crate rand; - use rand::thread_rng; use rand::Rng; fn main() { let mut rng = thread_rng(); for i in 1..10 { - println!("Random number #{}: {}", i, rng.gen_range(0, 100)); + println!("Random number #{}: {}", i, rng.gen_range(0..=100)); } } ``` @@ -81,8 +73,6 @@ fn main() { The generator can quickly fill an array with random integers. ```rust,editable -# extern crate rand; - use rand::thread_rng; use rand::Rng; @@ -97,8 +87,6 @@ Another neat feature of the generator is that it can generate random numbers from a probability distribution. ```rust,editable -# extern crate rand; - use rand::thread_rng; use rand::Rng; @@ -127,7 +115,7 @@ a web browser or in Node.js. To enable that, do the following in your `Cargo.tom ``` [dependencies] -rand = { version = "0.7.3", features = ["wasm-bindgen"] } +rand = { version = "0.8.5", features = ["wasm-bindgen"] } ``` Then you must use one of the [`wasm-bindgen`](https://rustwasm.github.io/docs/wasm-bindgen/) compatible tools to instrument