pub trait ActExtension
where
Self: Sized,
{
fn act(self, f: impl FnOnce(&Self)) -> Self {
f(&self);
self
}
fn act_mut(mut self, f: impl FnOnce(&mut Self)) -> Self {
f(&mut self);
self
}
}
impl<T> ActExtension for T where T: Sized {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn act() {
let a = String::from("1").act(|a| println!("{}", a));
assert_eq!(a, "1".to_string());
let a: Vec<usize> = [1, 2, 3]
.iter()
.map(|a| a + 1)
.act(|a| println!("{}", a.len()))
.collect();
assert_eq!(a, vec![2, 3, 4]);
}
#[test]
fn act_mut() {
let a = String::from("1").act_mut(|a| *a = "2".to_string());
assert_eq!(a, "2".to_string());
let a = vec![3, 2, 1].act_mut(|a| a.sort());
assert_eq!(a, vec![1, 2, 3]);
}
}