简体   繁体   English

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

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

Is there any way to implement operator overloading for apply::Apply ?有没有办法为apply::Apply实现运算符重载

In Rust, many of the operators can be overloaded via traits.在 Rust 中,许多运算符可以通过特征重载。 That is, some operators can be used to accomplish different tasks based on their input arguments.也就是说,一些算子可以根据他们的输入 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)).例如,a + b 中的 + 运算符调用 add 方法(如在 a.add(b) 中)。 This add method is part of the Add trait.这个 add 方法是 Add trait 的一部分。 Hence, the + operator can be used by any implementor of the Add trait.因此,任何 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板条箱过载

For instance,例如,

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

for为了

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

Not really.并不真地。 Operators don't go on traits, they go on types.运算符在特征上不 go,在类型上不 go。 It does not make sense to ask "what is the implementation of >> for Apply " but it does make sense to ask "what is the implementation of >> for u8 ."问“ >> for Apply的实现是什么”没有意义,但问“ >> for u8的实现是什么”确实有意义。 So what you could try to do is to define Apply as you've defined it, and now:所以你可以尝试做的是按照你定义的那样定义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)
    }
}

This almost works, except that the compiler reports an error, citing几乎可以工作,除了编译器报告错误,引用

only traits defined in the current crate can be implemented for a type parameter只能为类型参数实现当前 crate 中定义的特征

The reason for this error is that you have no guarantee that another crate has not implemented the same trait for the same type.这个错误的原因是你不能保证另一个 crate 没有为相同的类型实现相同的 trait。 If another crate defined a如果另一个箱子定义了一个

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

its not clear what should happen, since now the >> operator has been defined twice for the same type.不清楚应该发生什么,因为现在>>运算符已为同一类型定义了两次。 You could write such an impl if you replaced MyType with some specific type that is local to your crate, but of course now the >> thing won't work for all other types.如果您将MyType替换为您的板条箱本地的某些特定类型,您可以编写这样的impl ,但当然现在>>的东西不适用于所有其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM