Rust 中是否同时存在组合运算符和管道转发运算符 ( like in other languages )?如果是这样,它们看起来像什么,一个应该比另一个更受青睐?如果不存在,为什么不需要这个运算符?
最佳答案
没有内置这样的运算符,但定义起来并不是特别困难:
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
新型结构纯粹是为了允许 Shr
例如,否则我们将不得不在通用(即 impl<A, B> Shr<...> for A
)上实现它,这是行不通的。
请注意,惯用的 Rust 会将此方法称为 map
而不是使用运算符(operator)。参见 Option::map
举个典型的例子。
关于rust - Rust 中的组合运算符和管道转发运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054978/