在Rust语言中,组合运算符和管道前向运算符(像其他语言中的)是否都存在?如果是,它们看起来是什么样子的,应该优先选择哪一个?如果不存在,为什么不需要这个运算符?
虽然没有内置此运算符,但定义它并不特别困难:
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
),但这样做是行不通的。
map
来代替操作符。请参考 Option::map
的规范示例。虽然这些运算符本身并不存在,Option::map
提供了一个惯用的类比。
fn do_some_stuff_to_a_number(x: Option<i32>) -> Option<String> {
x.map(|x| x + 1).map(|x| 2 * x).map(|x: i32| x.to_string())
}
如果没有函数:
let string = Some(1)
.map(|x| x + 1)
.map(|x| 2 * x)
.map(|x: i32| x.to_string())?;
|>
? - mpen