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.rs222 chars11 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.
gistlibby LogSnag