Guest User

Untitled

a guest
Nov 17th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. use std::rc::Rc;
  2. use std::marker::PhantomData;
  3.  
  4. fn main() {
  5. let john = User { name: "John".to_owned(), age: 16 };
  6. let not_john = User { name: "Paul".to_owned(), age: 18 };
  7.  
  8. let prop_name = Property::new(&"name", User::name);
  9. let is_john = prop_name.eq("John".to_owned());
  10.  
  11. println!("{}", (is_john.predicate)(&john)); // should return true
  12. println!("{}", (is_john.predicate)(&not_john)); // should return false
  13.  
  14. }
  15.  
  16. struct User {
  17. name: String,
  18. age: i32,
  19. }
  20.  
  21. impl User {
  22. fn name(&self) -> String {
  23. self.name.to_owned()
  24. }
  25.  
  26. fn age(&self) -> i32 {
  27. self.age
  28. }
  29. }
  30.  
  31. struct Property<T, R> {
  32. name: String,
  33. selector: Rc<Fn(&T) -> R>,
  34. }
  35. impl<T, R> Property<T, R> {
  36. fn new<S: 'static>(name: &str, selector: S) -> Property<T, R>
  37. where S: Fn(&T) -> R {
  38. Property { name: name.to_owned(), selector: Rc::new(selector) }
  39. }
  40. }
  41.  
  42. struct Feature<T, F: Fn(&T) -> bool> {
  43. description: String,
  44.  
  45. // this gets rid of the unnecessary box, and allows
  46. // us to annotate the lifetime of the function
  47. predicate: F,
  48.  
  49. // treat this as extra necessary syntax if you don't understand it
  50. __phantom: PhantomData<T>
  51. }
  52.  
  53. impl<T, R: Eq> Property<T, R> {
  54. // note the impl Fn(&T) -> bool + '_
  55. // this means that we are making the compiler infer
  56. // the return type from the body of the function
  57. // '_ means that we are making the compiler infer
  58. // the correct lifetime (not 'static)
  59. fn eq(&self, data: R) -> Feature<T, impl Fn(&T) -> bool + '_> {
  60. Feature {
  61. description: self.name.to_owned() + "== fixed data",
  62. predicate: move |it: &T| (self.selector)(it) == data,
  63. __phantom: PhantomData
  64. }
  65. }
  66. }
Add Comment
Please, Sign In to add comment