Logo

Programming-Idioms

History of Idiom 11 > diff from v68 to v69

Edit summary for version 69 by GobbleCock:
New Rust implementation by user [GobbleCock]

Version 68

2018-05-08, 01:23:30

Version 69

2018-06-11, 19:30:25

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};
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.
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
Demo URL
https://play.rust-lang.org/?gist=b84ee25d8824dd5e6de907337afce901&version=stable&mode=debug