Get Random Enum Rust

[Solved] Get Random Enum Rust | Rust - Code Explorer | yomemimo.com
Question : get random enum rust

Answered by : huldar

Your own enum
Like most abstractions in Rust, random value generation is powered by traits. Implementing a trait is the same for any particular type, the only difference is exactly what the methods and types of the trait are.
Rand 0.5, 0.6, 0.7, and 0.8
Implement Distribution using your enum as the type parameter. You also need to choose a specific type of distribution; Standard is a good default choice. Then use any of the methods to generate a value, such as rand::random:
use rand::{ distributions::{Distribution, Standard}, Rng,
}; // 0.8.0
#[derive(Debug)]
enum Spinner { One, Two, Three,
}
impl Distribution<Spinner> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Spinner { // match rng.gen_range(0, 3) { // rand 0.5, 0.6, 0.7 match rng.gen_range(0..=2) { // rand 0.8 0 => Spinner::One, 1 => Spinner::Two, _ => Spinner::Three, } }
}
fn main() { let spinner: Spinner = rand::random(); println!("{:?}", spinner);
}

Source : https://stackoverflow.com/questions/48490049/how-do-i-choose-a-random-value-from-an-enum | Last Update : Fri, 24 Dec 21

Answers related to get random enum rust

Code Explorer Popular Question For Rust