Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 5 additions & 17 deletions src/rand.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@ 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

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);
Expand All @@ -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);
Expand All @@ -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));
}
```

Expand All @@ -65,24 +59,20 @@ 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));
}
}
```

The generator can quickly fill an array with random integers.

```rust,editable
# extern crate rand;

use rand::thread_rng;
use rand::Rng;

Expand All @@ -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;

Expand Down Expand Up @@ -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
Expand Down