是否可以为 apply::Apply 实现运算符重载?

Is it possible to implement operator overloading for apply::Apply?

有没有办法实现operator overloading for apply::Apply

In Rust, many of the operators can be overloaded via traits. That is, some operators can be used to accomplish different tasks based on their input arguments. This is possible because operators are syntactic sugar for method calls. For example, the + operator in a + b calls the add method (as in a.add(b)). This add method is part of the Add trait. Hence, the + operator can be used by any implementor of the Add trait.

/// Represents a type which can have functions applied to it (implemented
/// by default for all types).
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)
    }
}

impl<T: ?Sized, Res> Apply<Res> for T {
    // use default definitions...
}

Crate overload

例如,

let string = 1 >> (|x| x * 2) >> (|x: i32| x.to_string());

let string = 1.apply(|x| x * 2).apply(|x: i32| x.to_string());

不是真的。运营商不继续特质,他们继续类型。问“Apply>> 的实现是什么”没有意义,但问“u8>> 的实现是什么”确实有意义。 “所以你可以尝试做的是像你定义的那样定义 Apply,现在:

impl<T, Res, F> std::ops::Shr<F> for T
where
    T: Apply<Res>,
    F: FnOnce(T) -> Res
{
    type Output = Res;
    fn shr(self, rhs: F) -> Res {
        rhs(self)
    }
}

这个几乎可以工作,只是编译器报错,引用

only traits defined in the current crate can be implemented for a type parameter

这个错误的原因是你不能保证另一个 crate 没有为相同类型实现相同的特征。如果另一个 crate 定义了 a

impl<F: FnOnce(MyType) -> String> std::ops::Shr<F> for MyType { ... }

不清楚会发生什么,因为现在 >> 运算符已为同一类型定义了两次。如果您将 MyType 替换为您的板条箱本地的某些特定类型,您可以编写这样的 impl,但当然现在 >> 不适用于所有其他类型。