Skip to content

choose

Picks one element at random, each with the same probability.

use helpers4::random::choose;

Cargo feature random (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features random

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.9", default-features = false, features = ["random"] }
pub fn choose<'a, T>(items: &'a [T], rng: &mut Rng) -> Option<&'a T>
ParameterTypeDescription
items&'a [T]The elements to pick from.
rng&mut RngThe generator that decides the pick.

Option<&'a T> — A reference to the chosen element, or None when items is empty.

use helpers4::random::{choose, Rng};

let names = ["ana", "bo", "cy"];
let pick = choose(&names, &mut Rng::seeded(3));
assert!(pick.is_some_and(|name| names.contains(name)));
assert_eq!(choose::<u8>(&[], &mut Rng::seeded(3)), None);

src/random/choose.rs