Why core IO next() methods return Option<Result<T>> instead of Result<Option<T>>


#1

This is just curiosity about the design of the next() methods in the core IO module.

For example, I would expect file.lines().next() to return a Result<Option<String>>, it just feels more natural to me.

If the next line cannot be read for some reason I would expect to get an Err(...), while I would not expect to get a Some(Err(...)). In the other case, if I can actually read from the file without errors, then I would know if there’s a next line in the file or not, and I could return an Ok(Some(result)) or Ok(None).

What is the reason why it has been implemented the other way around? Any thoughts?


#2

Because next() is actually Iterator::next() (see the book’s chapter on iterators) and is not IO specific. Basically, lines() returns a standard iterator which yields an Option<T> for each call to next(). In this case, T is Result<String>.


#3

That makes perfect sense, thanks :slight_smile: