Your own listing
Like most abstractions in Rust, random value generation is trait-based. The implementation of the characteristic is the same for any particular type, the only difference is which methods and types of the characteristic are.
Rand 0.5, 0.6, and 0.7
Implement Distribution using your enumeration as a type parameter. You also need to select a specific type of distribution; Standard is a good default choice. Then use any of the methods to generate the value, for example rand::random :
use rand::{ distributions::{Distribution, Standard}, Rng, }; // 0.7.0
Rand 0.4
Implement Rand for your enumeration, then use any of the methods to generate the value, for example, Rng::gen :
extern crate rand; // 0.4.2 use rand::{Rand, Rng};
get
rand_derive may remove the need for this template, but does not exist for Rand 0.5.
extern crate rand; #[macro_use] extern crate rand_derive; use rand::Rng; #[derive(Debug, Rand)] enum Spinner { One, Two, Three, } fn main() { let mut rng = rand::thread_rng(); let spinner: Spinner = rng.gen(); println!("{:?}", spinner); }
Someone else enum
Since you do not control the enumeration, you must copy something into your code in order to reference it. You can create an array of enumerations and choose from this:
use rand::seq::SliceRandom; // 0.7.0 mod another_crate {
You can replicate the entire enumeration locally, implement Rand for this, and then have a method that converts back to the representation of other boxes.
use rand::{ distributions::{Distribution, Standard}, Rng, }; // 0.7.0 mod another_crate { #[derive(Debug)] pub enum Spinner { One, Two, Three, } } enum Spinner { One, Two, Three, } impl From<Spinner> for another_crate::Spinner { fn from(other: Spinner) -> another_crate::Spinner { match other { Spinner::One => another_crate::Spinner::One, Spinner::Two => another_crate::Spinner::Two, Spinner::Three => another_crate::Spinner::Three, } } } impl Distribution<Spinner> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Spinner { match rng.gen_range(0, 3) { 0 => Spinner::One, 1 => Spinner::Two, _ => Spinner::Three, } } } fn main() { let spinner = another_crate::Spinner::from(rand::random::<Spinner>()); println!("{:?}", spinner); }
You can count the number of spinners and make a match:
use rand::Rng; // 0.7.0 mod another_crate {
You can implement a new type and implement random generation for this:
use rand::{distributions::Standard, prelude::*}; // 0.7.0 mod another_crate {
See also: