[−][src]Trait turtle::rand::Random
This trait represents any type that can have random values generated for it.
Tip: There is a list later on this page that shows many of the types that implement this trait.
Example
To implement this trait for your own types, call random()
or random_range()
for each field.
For enums, generate a random number and pick a variant of your enum based on that. You can then
use random()
or random_range()
to pick values for that variant's fields (if necessary).
use turtle::rand::{ random, random_range, Random, RandomRange, }; #[derive(Debug, Clone)] struct Product { price: f64, quantity: u32, } impl Random for Product { fn random() -> Self { Self { // Prices sure are fluctuating! price: Random::random(), // This will generate a value between 1 and 15 (inclusive) quantity: RandomRange::random_range(0, 15), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Door { Open, Closed, Locked, } impl Random for Door { fn random() -> Self { use Door::*; // Pick a variant of `Door` based on a number. // Notice the type in the numeric literal so Rust knows what to generate match RandomRange::random_range(0u8, 3) { 0 => Open, 1 => Closed, 2 => Locked, // Even though we know that the value will be between 0 and 2, the compiler does // not, so we instruct it to panic if this case ever occurs. _ => unreachable!(), } } } fn main() { // These types can now be used with the `random()` function! let product: Product = random(); let door: Door = random(); // ... }
Required methods
fn random() -> Self
Generate a single random value.
Example
use turtle::{Color, Speed, rand::random}; // Need to annotate the type so Rust knows what you want it to generate let x: f32 = random(); let y: f32 = random(); // Works with turtle specific types too! let color: Color = random(); let speed: Speed = random();