Logo

Programming-Idioms

History of Idiom 11 > diff from v70 to v71

Edit summary for version 71 by programming-idioms.org:
[Rust] Variable name x. No sample values. Comments emphasis.

Version 70

2018-06-11, 19:30:57

Version 71

2018-08-03, 20:33:59

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 choice = thread_rng().choose(&x).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 x 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