Rust 通过重载操作器对任何管道操作器进行防锈处理

Rust 通过重载操作器对任何管道操作器进行防锈处理,rust,Rust,但有明显的错误 我怎样才能解决这个问题?谢谢。谢谢@mcarton 我找到了一个类似的解决方案: pub特性应用{ ///应用按值获取参数的函数。 fn应用Res>(self,f:f)->Res 哪里 自我:大小, { f(自我) } ///应用通过引用获取参数的函数。 fn应用\u ref Res>(&self,f:f)->Res{ f(自我) } ///应用通过可变引用获取参数的函数。 fn应用_mutres>(&mut self,f:f)->Res{ f(自我) } } impl申请T

但有明显的错误

我怎样才能解决这个问题?谢谢。

谢谢@mcarton

我找到了一个类似的解决方案:

pub特性应用{
///应用按值获取参数的函数。
fn应用Res>(self,f:f)->Res
哪里
自我:大小,
{
f(自我)
}
///应用通过引用获取参数的函数。
fn应用\u ref Res>(&self,f:f)->Res{
f(自我)
}
///应用通过可变引用获取参数的函数。
fn应用_mutres>(&mut self,f:f)->Res{
f(自我)
}
}
impl申请T{
//使用默认定义。。。
}
fn main(){
设字符串=1
.应用(|x | x*2)
.应用(|x | x+1)
.apply(|x:i32 | x.to_string());
println!(“{}”,字符串);
}
多亏了@mcarton

我找到了一个类似的解决方案:

pub特性应用{
///应用按值获取参数的函数。
fn应用Res>(self,f:f)->Res
哪里
自我:大小,
{
f(自我)
}
///应用通过引用获取参数的函数。
fn应用\u ref Res>(&self,f:f)->Res{
f(自我)
}
///应用通过可变引用获取参数的函数。
fn应用_mutres>(&mut self,f:f)->Res{
f(自我)
}
}
impl申请T{
//使用默认定义。。。
}
fn main(){
设字符串=1
.应用(|x | x*2)
.应用(|x | x+1)
.apply(|x:i32 | x.to_string());
println!(“{}”,字符串);
}

回答了你的问题吗?@mcarton是的,我的意思是不,这没有帮助。。。您是否认为不可能在任何计算机上实现重载运算符?谢谢。是的,这是不可能的。此外,对任何类型实现trait的常用方法是
impl trait for T
,而不是使用
any
。好的,谢谢你,我明白了。我想知道是否有一个解决办法,或者希望这个自定义操作符可以像Haskell一样。回答你的问题了吗?@mcarton是的,我的意思是不,它没有帮助。。。您是否认为不可能在任何计算机上实现重载运算符?谢谢。是的,这是不可能的。此外,对任何类型实现trait的常用方法是
impl trait for T
,而不是使用
any
。好的,谢谢你,我明白了。我想知道是否有一个解决办法,或者希望这个自定义操作符可以像Haskell一样。
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`
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)
    }
}
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);
}