rust

How can I randomly select one element from a vector or array?


I have a vector where the element is a (String, String). How can I randomly pick one of these elements?


Solution

  • You want the rand crate, specifically the choose method.

    use rand::seq::IndexedRandom; // 0.9.0
    
    fn main() {
      let vs = vec![0, 1, 2, 3, 4];
      match vs.choose(&mut rand::rng()) {
        Some(i) => println!("{}", i),
        None    => println!("Nothing!")
      }
    }