Logo

Programming-Idioms

History of Idiom 11 > diff from v69 to v70

Edit summary for version 70 by GobbleCock:
[Rust] Add missing semicolon

Version 69

2018-06-11, 19:30:25

Version 70

2018-06-11, 19:30:57

Idiom #11 Pick a random element from a list

List x must be non-empty.

Illustration

Idiom #11 Pick a random element from a list

List x must be non-empty.

Illustration
Extra Keywords
choose
Extra Keywords
choose
Imports
extern crate rand;
use rand::{thread_rng, Rng};
Imports
extern crate rand;
use rand::{thread_rng, Rng};
Code
let choices = [1, 2, 4, 8, 16, 32];
let choice = thread_rng().choose(&choices).unwrap()
Code
let choices = [1, 2, 4, 8, 16, 32];
let choice = thread_rng().choose(&choices).unwrap();
Comments bubble
Requires the rand crate.
(https://crates.io/crates/rand)

The choose method returns an Option which is None if the given list is empty.
Comments bubble
Requires the rand crate.
(https://crates.io/crates/rand)

The choose method returns an Option which is None if the given list is empty.
Doc URL
https://docs.rs/rand/0.5.1/rand/trait.Rng.html#method.choose
Doc URL
https://docs.rs/rand/0.5.1/rand/trait.Rng.html#method.choose
Origin
https://docs.rs/rand/0.5.1/rand/trait.Rng.html#example-7
Origin
https://docs.rs/rand/0.5.1/rand/trait.Rng.html#example-7
Demo URL
https://play.rust-lang.org/?gist=b84ee25d8824dd5e6de907337afce901&version=stable&mode=debug
Demo URL
https://play.rust-lang.org/?gist=b84ee25d8824dd5e6de907337afce901&version=stable&mode=debug