gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:41:25 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com