Rust 中的组合运算符和管道转发运算符 [英] Composition operator and pipe forward operator in Rust

查看:119
本文介绍了Rust 中的组合运算符和管道转发运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时执行组合和管道转发操作符(就像在其他语言中一样) 存在于 Rust 中?如果是这样,它们看起来像什么,一个应该比另一个更受欢迎吗?如果不存在,为什么不需要这个运算符?

Do both the composition and pipe forward operators (like in other languages) exist in Rust? If so, what do they look like and one should one be preferred to the other? If one does not exist, why is this operator not needed?

推荐答案

没有内置这样的操作符,但定义并不是特别难:

There is no such operator built-in, but it's not particularly hard to define:

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) 并且这不起作用.

The Wrapped new-type struct is purely to allow the Shr instance, because otherwise we would have to implement it on a generic (i.e. impl<A, B> Shr<...> for A) and that doesn't work.

请注意,惯用的 Rust 会将其称为方法 map 而不是使用运算符.参见 Option::map 一个典型的例子.

Note that idiomatic Rust would call this the method map instead of using an operator. See Option::map for a canonical example.

这篇关于Rust 中的组合运算符和管道转发运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆