【发布时间】:2023-04-06 09:41:02
【问题描述】:
在这个函数中parse 可以返回错误,所以我使用.filter_map(Result::ok) 过滤掉它们。
fn part1(input: &str) {
let sum = input.lines()
.map(|l| l.parse::<u32>())
.filter_map(Result::ok)
.map(|n| n as f32 / 3.0)
.map(|f| f.round())
.map(|f| f as u32 - 2)
.sum::<u32>();
// println!("{}", sum);
println!("{:?}", sum);
}
但是,当 parse 出现错误时,我想退出 part1 函数,有点像使用像 .map(|l| l.parse::<u32>()?) 这样的问号运算符。如果这样做,编译器会给出错误
error[E0277]: the `?` operator can only be used in a closure that returns `Result`
or `Option` (or another type that implements `std::ops::Try`)
--> src/main.rs:64:18
|
64 | .map(|l| l.parse::<u32>()?)
| ----^^^^^^^^^^^^^^^^^
| | |
| | cannot use the `?` operator in a closure that returns `u32`
| this function should return `Result` or `Option` to accept `?`
这是因为问号运算符在闭包内使用,所以它从闭包而不是封闭函数返回?在闭包内使用问号运算符有哪些惯用的替代方法,以便如果 parse 给出错误,我可以从 part1 返回,或者如果解析成功,则打开 Ok?结果应该类似于.filter_map(Result::ok),除了它不会过滤掉错误,而是会在出现错误时从封闭函数中返回。
【问题讨论】:
-
附注:与 Chris 相比,恕我直言,拥有多个
map电话比拥有一个大块更好。所以保留它;) -
@hellow 删除对 map 的调用可悲地摆脱了计算的管道感觉,这几乎使它感觉更清晰。但我坚持我的建议,因为我更喜欢计算不与迭代器方法捆绑在一起。不过我明白你的意思!
-
Rust by example 提供了一些很好的模式:doc.rust-lang.org/rust-by-example/error/iter_result.html
标签: rust