Rust中的合成运算符和管道转发运算符

Phl*_*das 19 rust

Rust中是否存在组合和管道转发操作符(如其他语言)?如果是这样,它们看起来像什么,而另一个应该优先考虑?如果不存在,为什么不需要这个操作符?

huo*_*uon 23

内置没有这样的运算符,但定义起来并不是特别困难:

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`
Run Code Online (Sandbox Code Playgroud)

Wrapped新型结构是完全允许的Shr情况下,否则我们就必须实现它在通用(即impl<A, B> Shr<...> for A)和不工作.


请注意,惯用Rust会将此称为方法,map而不是使用运算符.请参阅Option::map规范示例.

  • 这不再编译了.'自我不再是特殊的一生.当前生锈有没有办法做到这一点? (2认同)