[英]Why don't we need to extract values from Result in some rust iterators?
Here, I have a simple map and sum over an iterator: 在这里,我有一个简单的映射并通过迭代器求和:
fn main() {
let s = "
aoeu
aoeu
aoeu
aoeu
";
let ls = s.lines();
let i: usize = ls.map(|l| l.len()).sum();
dbg!(i);
}
This compiles and runs fine. 这样可以编译并正常运行。 When I look at the source for lines
, the next
method returns Option<Result<String>>
. 当我查看lines
的源代码时 , next
方法将返回Option<Result<String>>
。
But the map above calls .len()
directly on each item. 但是上面的地图直接在每个项目上调用.len()
。 I understand the value is extracted from inside the Option
(a None
value would mean the end of the iterator). 我知道该值是从Option
内部提取的( None
值表示迭代器的结尾)。 Is .len()
being called on the Result
object? 是否在Result
对象上调用.len()
? Why don't we need to call something like map()
* to extract the value from Result
? 为什么我们不需要调用诸如map()
*之类的东西来从Result
提取值?
Thanks! 谢谢!
* I had thought Result::map
had a different meaning to Iterator::map
, but maybe I'm confusing myself... *我以为Result::map
与Iterator::map
含义有所不同,但也许让我感到困惑...
There are two lines
in the standard library. 标准库中有两lines
。
The one on str
, which returns std::str::Lines
, which is an iterator of &str
. str
上的一个 ,返回std::str::Lines
,它是&str
的迭代器。 This is the one you are using. 这是您正在使用的那个。 Splitting a string cannot fail, so it doesn't need to use Result
. 分割字符串不会失败,因此不需要使用Result
。
And the one on std::io::BufRead
, which returns std::io::Lines
. 还有一个在std::io::BufRead
,它返回std::io::Lines
。 This one reads from a BufRead
, which can fail (eg. reading a file on a network drive can fail if the drive becomes unreachable), so it must return a Result
. 这是从BufRead
读取的,这可能会失败(例如,如果驱动器变得无法访问,则读取网络驱动器上的文件可能会失败),因此它必须返回Result
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.