Created
March 26, 2025 14:29
-
-
Save toddlers/ae657fe19547c6c0868915c4af99a662 to your computer and use it in GitHub Desktop.
call pipe on any type, pass a closure and process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt::Display; | |
trait Pipe:Sized { | |
fn pipe<F,R>(self, f:F) -> R | |
where | |
F: FnOnce(Self) -> R; | |
fn pipe_ref<F,R>(&self, f:F) -> R | |
where | |
F: FnOnce(&Self) -> R; | |
fn pipe_mut<'a, F,R>(&'a mut self, f:F) -> R | |
where | |
F: FnOnce(&'a mut Self) -> R; | |
} | |
impl <T> Pipe for T{ | |
#[inline(always)] | |
fn pipe<F,R>(self, f:F) -> R | |
where F: FnOnce(Self) -> R { | |
f(self) | |
} | |
#[inline(always)] | |
fn pipe_ref<F,R>(&self, f:F) -> R | |
where F: FnOnce(&Self) -> R { | |
f(self) | |
} | |
fn pipe_mut<'a, F,R>(&'a mut self, f:F) -> R | |
where | |
F: FnOnce(&'a mut Self) -> R{ | |
f(self) | |
} | |
} | |
fn add(x: i32, y: i32) -> i32 { | |
x + y | |
} | |
fn add_element(vec: &mut Vec<i32>, item: i32) -> &mut Vec<i32> { | |
vec.push(item); | |
vec | |
} | |
fn add_string(string1: impl AsRef<str> + Display, string2: &str) -> String{ | |
format!("{} {}!", string1,string2) | |
} | |
fn main() { | |
// let temp = 5; | |
// let out = temp.pipe(|x|{ | |
// add(x,10); | |
// dbg!(temp) | |
// }); | |
// // assert_eq!(out, 15); | |
// // println!("Pipe Result: {:?}", out); | |
// let v = vec![1,2,3]; | |
// let out = v.pipe(|f| { | |
// // println!("{:?}", f); | |
// // println!("{:?}", v); | |
// }); | |
// println!("Pipe Result: {:?}", out); | |
let s = "hello ".to_string(); | |
let out = s.pipe_ref(|s| add_string(s, " world!")); | |
let out1 = s.pipe_ref(|s| add_string(s, " world!")); | |
println!("Pipe Result: {:?}", out); | |
println!("Pipe Result: {:?}", out1); | |
let mut v = vec![1, 2, 3]; | |
// Using pipe_ref to avoid moving | |
v.pipe_ref(|vec_ref| { | |
println!("Vector contents: {:?}", vec_ref); | |
}); | |
// Still valid because v was not moved | |
println!("Still usable: {:?}", v); | |
v.pipe_mut(|vec_mut| add_element(vec_mut, 5)) | |
.pipe_ref(|vec| {println!("Still usable: {:?}", vec)}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment