pub trait Tap: Sized {
fn tap<F: FnOnce(&mut Self)>(mut self, f: F) -> Self {
f(&mut self);
self
}
}
impl<T> Tap for T {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tap_with_integer() {
let result = 5.tap(|x| *x += 1).tap(|x| *x *= 2);
assert_eq!(result, 12);
}
#[test]
fn test_tap_with_vector() {
let vec = vec![1, 2, 3];
let tapped_vec = vec.tap(|v| v.push(4)).tap(|v| v.sort_by(|a, b| b.cmp(a)));
assert_eq!(tapped_vec, vec![4, 3, 2, 1]);
}
#[test]
fn test_tap_with_string() {
let string = String::from("hello");
let tapped_string = string.tap(|s| s.push_str(", world")).tap(|s| s.make_ascii_uppercase());
assert_eq!(tapped_string, "HELLO, WORLD");
}
}