Advertisement
NLinker

Generic random with Option

Jul 6th, 2018
455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.86 KB | None | 0 0
  1. // https://play.rust-lang.org/?gist=00a5ed94a488279e73167c48c444761c
  2. // Fix
  3.  
  4. extern crate rand;
  5.  
  6. use rand::prelude::{Rng, ThreadRng};
  7.  
  8. #[derive(Clone, Copy, Eq, PartialEq, Debug)]
  9. pub enum Move {
  10.     Right, Up, Left, Down, Stop,
  11. }
  12.  
  13. fn main() {
  14.    
  15.     let m1 = random_move_if::<ThreadRng>(None);
  16.    
  17.     let mut rng: Option<ThreadRng> = Some(rand::thread_rng());
  18.     let m2 = random_move_if(rng.as_mut());
  19.    
  20.     println!("m1, m2 = {:?}, {:?}", m1, m2);
  21.  
  22. }
  23.  
  24. fn random_move_if<R: Rng>(random: Option<&mut R>) -> Move {
  25.     let moves = vec![Move::Right, Move::Up, Move::Left, Move::Down];
  26.  
  27.     // match random {
  28.     //     None => Move::Stop,
  29.     //     Some(r) => moves[r.gen_range(0, moves.len())],
  30.     // }
  31.     if random.is_some() {
  32.         let r = random.unwrap();
  33.         moves[r.gen_range(0, 4)]
  34.     } else {
  35.         Move::Stop
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement