1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
pub trait ScopeFunc: Sized { fn transform<F, R>(self, f: F) -> R where F: FnOnce(Self) -> R, { f(self) } fn modify<F>(mut self, f: F) -> Self where F: FnOnce(&mut Self), { f(&mut self); self } fn inspect<F>(self, f: F) -> Self where F: FnOnce(&Self), { f(&self); self } } impl<T> ScopeFunc for T {} #[cfg(test)] mod tests { use super::*; #[test] fn it_works() { fn get_string() -> String { "hello".to_string() } fn to_iter(s: String) -> impl Iterator<Item = char> { s.chars().collect::<Vec<_>>().into_iter() } assert_eq!( "hello", get_string().transform(|s| to_iter(s)).collect::<String>() ); assert_eq!("HELLO", get_string().modify(|s| s.make_ascii_uppercase())); } }