简体   繁体   中英

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>> .

But the map above calls .len() directly on each item. I understand the value is extracted from inside the Option (a None value would mean the end of the iterator). Is .len() being called on the Result object? Why don't we need to call something like map() * to extract the value from Result ?

Thanks!

* I had thought Result::map had a different meaning to Iterator::map , but maybe I'm confusing myself...

There are two lines in the standard library.

The one on str , which returns std::str::Lines , which is an iterator of &str . This is the one you are using. Splitting a string cannot fail, so it doesn't need to use Result .

And the one on std::io::BufRead , which returns 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM