To retrieve a random item from a set in Rust, you can use the `rand` crate along with the `thread_rng()` function and `choose()` method.
In this example,
[dependencies]
rand = "0.8.4"
use rand::{thread_rng, seq::SliceRandom};
fn main() {
// Create and populate the set (vector or array)
let mut my_set = vec![1, 2, 3, 4, 5];
// Initialize the random number generator
let mut rng = thread_rng();
// Get random item from set
if let Some(random_item) = my_set.choose(&mut rng) {
// Print random item
println!("Random item from set: {}", random_item);
} else {
println!("Set is empty");
}
}
Random item from set: [random value]
In this example,
use rand::{seq::SliceRandom, thread_rng};
fn main() {
// Create and populate the set (vector or array)
let mut my_set = vec![1, 2, 3, 4, 5];
// Initialize the random number generator
let mut rng = thread_rng();
// Specify number of random items
let num_random_items = 3;
// Shuffle the set
my_set.shuffle(&mut rng);
// Get multiple random items from set
let random_items: Vec<_> = my_set.iter().take(num_random_items).collect();
// Print random items
println!("Random items from set: {:?}", random_items);
}
Random items from set: [random value 1, random value 2, random value 3]
In this tutorial, we learned How to get a Random Item in a Set in Rust language with well detailed examples.