【发布时间】:2022-01-12 21:03:31
【问题描述】:
有没有办法为apply::Apply实现operator overloading?
在 Rust 中,许多运算符可以通过特征重载。也就是说,一些运算符可用于根据其输入参数完成不同的任务。这是可能的,因为运算符是方法调用的语法糖。例如,a + b 中的 + 运算符调用 add 方法(如在 a.add(b) 中)。这个 add 方法是 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...
}
例如,
let string = 1 >> (|x| x * 2) >> (|x: i32| x.to_string());
为
let string = 1.apply(|x| x * 2).apply(|x: i32| x.to_string());
【问题讨论】:
-
“实现运算符重载”是什么意思?您始终可以在
std::ops中实现特征。 -
我想我的问题说清楚了,术语来自官方文档。
标签: rust functional-programming operator-overloading