[英]Rust pipeline operator for Any by overloading operators
Composition operator and pipe forward operator in Rust 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
.这是结构的管道运算符代码:通过重载运算符Wrapped
,但我需要一个可用于我认为是&dyn Any
本机值的代码。
Since I don't understand type system of Rust yet, so I did like由于我还不了解 Rust 的类型系统,所以我确实喜欢
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,感谢@mcarton,
Rust pipeline operator for Any by overloading operators 通过重载运算符用于 Any 的 Rust 管道运算符
I found a similar solution:我找到了一个类似的解决方案:
https://docs.rs/apply/0.3.0/apply/trait.Apply.html 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.