Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created September 15, 2019 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/07fa435c700c1dfab4c112cc07d1543d to your computer and use it in GitHub Desktop.
Save rust-play/07fa435c700c1dfab4c112cc07d1543d to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::ops::Add;
trait Pipeline<T> {
fn pipe(self, data: T) -> T;
}
impl<T, U> Pipeline<T> for U
where
U: IntoIterator,
U::Item: Fn(T) -> T,
{
fn pipe(self, data: T) -> T {
let mut result = data;
for apply_on in self.into_iter() {
result = apply_on(result);
}
result
}
}
fn main() {
let add1 = add(1);
let add2 = add(2);
let add3 = add(3);
let pipeline = vec![&add1, &add2, &add3];
let result = pipeline.pipe(1);
println!("{}", result); // prints 7
}
fn add<T>(x: T) -> impl Fn(T) -> T
where
T: Add<Output = T> + Copy,
{
move |y: T| x + y
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment