Guest User

Untitled

a guest
Jun 20th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. use std::collections::HashMap;
  2.  
  3. trait CCmdT {
  4. fn call(&self, Vec<&str>);
  5. }
  6.  
  7. struct CCmd<T>
  8. {
  9. func: Box<Fn(T, Vec<&str>) + 'static>
  10. }
  11.  
  12. impl<T: From<i32>> CCmdT for CCmd<T> {
  13. fn call(&self, args: Vec<&str>) {
  14. (self.func)(T::from(8), args);
  15. }
  16. }
  17.  
  18. struct Console {
  19. ccmds: HashMap<String, Box<CCmdT>>,
  20. }
  21.  
  22. impl Console {
  23. pub fn register<T: From<i32> + 'static>(&mut self, name: &str, func: Box<Fn(T, Vec<&str>) + 'static>) {
  24. let ccmd = CCmd { func: func };
  25. self.ccmds.insert(String::from(name), Box::new(ccmd));
  26. }
  27.  
  28. pub fn call(&self, name: &str, args: Vec<&str>) {
  29. if let Some(ccmd) = self.ccmds.get(name) {
  30. ccmd.call(args);
  31. }
  32. }
  33. }
  34.  
  35. fn main() {
  36. let mut console = Console {ccmds: HashMap::new()};
  37. console.register("foo", Box::new(|n: i32, args: Vec<&str>| println!("{} {}", n, args[1])));
  38. console.call("foo", vec!["foo", "bar", "baz"]);
  39. //register(Box::new(|n: &mut f32| println!("{}", n)));
  40. }
Add Comment
Please, Sign In to add comment