Advertisement
NLinker

Pass closures to functions

May 25th, 2018
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.95 KB | None | 0 0
  1. // https://play.rust-lang.org/?gist=9f1f7358288467c49d79f792c9ddf35c&version=stable&mode=debug
  2. fn main() {
  3.     let f: Box<Fn(&str) -> String> = Box::new(|s| s.to_owned());
  4.     func0(f);
  5.     let f: Box<Fn(&str) -> String> = Box::new(|s| s.to_owned());
  6.     func1(f);
  7.     let f: Box<Fn(&str) -> String> = Box::new(|s| s.to_owned());
  8.     func2(f.as_ref());
  9.     let f: Box<Fn(&str) -> String> = Box::new(|s| s.to_owned());
  10.     // func3(f); // TODO how to use impl trait here?
  11.     assert_eq!(hrtb(|x| x * 2), 22*2 + 44*2);
  12. }
  13.  
  14. fn hrtb(f: impl Fn(&u32) -> u32) -> u32 {
  15.     f(&22) + f(&44)
  16. }
  17.  
  18. fn func0(f: Box<Fn(&str) -> String>) {
  19.     println!("Call func: {}", f("test"));
  20. }
  21.  
  22. fn func1<F>(f: Box<F>) where F: Fn(&str) -> String + ?Sized {
  23.     println!("Call func: {}", f("test"));
  24. }
  25.  
  26. fn func2(f: &Fn(&str) -> String) {
  27.     println!("Call func: {}", f("test"));
  28. }
  29.  
  30. fn func3(f: impl Fn(&str) -> String) {
  31.     println!("Call func: {}", f("test"))
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement