get random enum rust
To get a random enum value in Rust, you can use the rand
crate and its Rng
trait. First, add the rand
crate to your Cargo.toml
file:
[dependencies]
rand = "0.8"
Then, in your code, you can use the rand::Rng
trait to generate a random enum value. Here's an example:
use rand::Rng;
#[derive(Debug)]
enum MyEnum {
Variant1,
Variant2,
Variant3,
}
fn main() {
let mut rng = rand::thread_rng();
let random_enum: MyEnum = match rng.gen_range(0..=2) {
0 => MyEnum::Variant1,
1 => MyEnum::Variant2,
_ => MyEnum::Variant3,
};
println!("{:?}", random_enum);
}
In this example, we import the Rng
trait from the rand
crate and define an enum called MyEnum
with three variants. Inside the main
function, we create a rand::thread_rng()
instance to generate random numbers. We then use the gen_range
method to generate a random number between 0 and 2 (inclusive). Based on the generated number, we match it to one of the enum variants and assign the result to the random_enum
variable. Finally, we print the value of random_enum
.
This code will output a random enum variant each time it is run.