rust - Rust 中的组合运算符和管道转发运算符

标签 rust

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/

相关文章:

c++ - 如何在 Rust 中静态链接 node.js?

rust - FuturesUnordered 的终身问题

casting - 如何将 Vec<&mut T> 转换为 Vec<&T>?

recursion - "Overflow evaluating the requirement"是什么意思,我该如何解决?

rust - 如何创建 DST 类型?

rust - 如何指定依赖项的确切版本?

rust - 为什么 `find` 通过引用获取参数然后取消引用它?

error-handling - 如何将自定义失败与失败箱匹配

rust - 为 u8 数组的返回值保留变量的生命周期

html - 如何使用 Wasm 和 Rust 来服务多个 HTML 页面?