[英]Rust pipeline operator for Any by overloading operators
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`
這是結構的管道運算符代碼:通過重載運算符Wrapped
,但我需要一個可用於我認為是&dyn Any
本機值的代碼。
由於我還不了解 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)
}
}
但有明顯的錯誤。
我該如何解決這個問題? 謝謝。
感謝@mcarton,
我找到了一個類似的解決方案:
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.