Horje
get random enum rust Code Example
get random enum rust

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);
}




Rust

Related
rust implement debug for struct Code Example rust implement debug for struct Code Example
rust string to &str Code Example rust string to &str Code Example
how to open a file rust Code Example how to open a file rust Code Example
deconstruct hashmap into vecs rust Code Example deconstruct hashmap into vecs rust Code Example
whats the difference between Iter and into_iter rust Code Example whats the difference between Iter and into_iter rust Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
14