Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.77 KB | None | 0 0
  1. trait Pipe
  2. where
  3. Self: Sized,
  4. {
  5. fn pipe<'a, F, R>(&'a self, f: F) -> R
  6. where
  7. F: Fn(&'a Self) -> R,
  8. {
  9. f(self)
  10. }
  11.  
  12. fn pipe_mut<'a, F>(&'a mut self, f: F) -> &'a mut Self
  13. where
  14. F: Fn(&mut Self),
  15. {
  16. f(self);
  17. self
  18. }
  19.  
  20. fn pipe_move<F, R>(self, f: F) -> R
  21. where
  22. F: Fn(Self) -> R,
  23. {
  24. f(self)
  25. }
  26. }
  27.  
  28. impl<T> Pipe for T {}
  29.  
  30. fn main() {
  31. assert!(1.pipe_move(inc).pipe(|x| x * x) == 4);
  32.  
  33. let mut v = vec![240, 159, 146, 150];
  34. assert_eq!(v.pipe(std::str::from_utf8), Ok("💖"));
  35.  
  36. v.pipe_mut(append_one).pipe_mut(append_one);
  37. assert_eq!(v, vec![240, 159, 146, 150, 1, 1]);
  38.  
  39.  
  40. }
  41.  
  42. fn inc(i: i64) -> i64 {
  43. i + 1
  44. }
  45.  
  46. fn append_one(v: &mut Vec<u8>) {
  47. v.push(1);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement