HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayrandomlyhowfromelementvectorcanoneselect

Problem

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!")
  }
}

Code Snippets

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!")
  }
}

Context

Stack Overflow Q#34215280, score: 123

Revisions (0)

No revisions yet.