Search
 
SCRIPT & CODE EXAMPLE
 

RUST

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

PREVIOUS NEXT
Code Example
Rust :: rust dictionary 
Rust :: cargo insall cargo-cahe this version of Cargo is older than the `2021` edition, and only supports `2015` and `2018` editions. 
Rust :: exit program rust 
Rust :: deconstruct hashmap into vecs rust 
Rust :: how to read from stdin rust 
Rust :: rust copy trait 
Rust :: making a web server in rust 
Rust :: rust .0 
Rust :: closure rust 
Rust :: rust create directory if not exists 
Rust :: rust javascript 
Rust :: rust lang start a new project 
Rust :: rust get input on the same line as question 
Rust :: rust comment types 
Rust :: rust count distinct elements in list 
Rust :: armanriazi•rust•concept•dynamic•dispatch 
Rust :: armanriazi•rust•error•E0308•mismatched types expected type parameter ``, found associated type 
Rust :: rust create hashmap from delimited data in string 
Rust :: rmarmanriazi•rust•concept•polymorphism 
Rust :: armanriazi•rust•concept•datarace•rustaceans 
Rust :: armanriazi•rust•comparison•generic•associated type 
Lua :: roblox rainbow part 
Lua :: lua pcall 
Lua :: lua wrap number 
Lua :: roblox go thru all players 
Lua :: return lua 
Lua :: lua how to add something to a table 
Lua :: lua empty table 
Lua :: roblox format string 
Lua :: What percentage of developers use Lua 
ADD CONTENT
Topic
Content
Source link
Name
7+9 =