Maximilian
Maximilian

Reputation: 8500

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

Upvotes: 1

Views: 231

Answers (1)

mcarton
mcarton

Reputation: 30021

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.

Upvotes: 6

Related Questions