Composition operator and pipe forward operator in Rust
use std::ops::Shr;
struct Wrapped<T>(T);
impl<A, B, F> Shr<F> for Wrapped<A>
where
F: FnOnce(A) -> B,
{
type Output = Wrapped<B>;
fn shr(self, f: F) -> Wrapped<B> {
Wrapped(f(self.0))
}
}
fn main() {
let string = Wrapped(1) >> (|x| x + 1) >> (|x| 2 * x) >> (|x: i32| x.to_string());
println!("{}", string.0);
}
// prints `4`
Here's a code of pipeline operator for struct: Wrapped
by overloading an operator, but I need one that can be used for native values that I think as &dyn Any
.
Since I don't understand type system of Rust yet, so I did like
use std::any::Any;
impl<A, B, F: Fn(A) -> B> Shr<F> for &dyn Any {
type Output = &dyn Any;
fn shr(self, f: F) -> &dyn Any {
f(self.0)
}
}
but with obvious errors.
How can I sort this out? Thanks.
Thanks to @mcarton,
Rust pipeline operator for Any by overloading operators
I found a similar solution:
https://docs.rs/apply/0.3.0/apply/trait.Apply.html
pub trait Apply<Res> {
/// Apply a function which takes the parameter by value.
fn apply<F: FnOnce(Self) -> Res>(self, f: F) -> Res
where
Self: Sized,
{
f(self)
}
/// Apply a function which takes the parameter by reference.
fn apply_ref<F: FnOnce(&Self) -> Res>(&self, f: F) -> Res {
f(self)
}
/// Apply a function which takes the parameter by mutable reference.
fn apply_mut<F: FnOnce(&mut Self) -> Res>(&mut self, f: F) -> Res {
f(self)
}
}
impl<T: ?Sized, Res> Apply<Res> for T {
// use default definitions...
}
fn main() {
let string = 1
.apply(|x| x * 2)
.apply(|x| x + 1)
.apply(|x: i32| x.to_string());
println!("{}", string);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.