get a random element from an array in rust

To get a random element from an array in Rust, you can use the rand crate. Here's an example of how to do it:

main.rs
use rand::seq::SliceRandom;

fn main() {
    let arr = [1, 2, 3, 4, 5];

    let mut rng = rand::thread_rng();
    let random_element = arr.choose(&mut rng).unwrap();

    println!("Random element: {}", random_element);
}
222 chars
11 lines

In this example, we first import the SliceRandom trait from the rand::seq module. This trait allows us to use the choose method to get a random element from a slice (which includes arrays).

We then create an array of integers arr and initialize it with some values.

Next, we create a thread_rng using rand::thread_rng(). This provides us with a random number generator that is suitable for use on the current thread.

Finally, we use the choose method on arr to get a random element, passing in a mutable reference to the random number generator. The choose method returns an Option, so we use the unwrap method to get the actual value.

We then print out the random element.

related categories

gistlibby LogSnag