Strange compiler error with `?` operator, closure and type inference

I was writing some code in Rust, when I got an error. I solved it but I don't understand the error

fn main() {
let cursor = io::Cursor::new(b"lorem\nipsum\r\ndolor");
let lines_iter = cursor
    .map(|line| /*-> io::Result<String>*/ {Ok(format!("{}", line?))});
//              -------------------------The solution was to add this
//                                       code (uncommented)

Edit: link to the playground
The compiler suggest me to add an explicit type Map<> to lines_iter, but with a really long type in the <>.
I don't understand with the compiler can't guess the return type of the closure. I return either Ok(String), with the string returned by format!, or an error returned by the ? operator if the line is an error. Can someone explain it to me ?

The thing that it is not able to figure out is the type of the error in the result. This is because the question mark operator will try to convert the error type if it doesn't match, so the only hint it currently has for the error type is that it is some error type that an IO error can be converted into.

Another way to hint it is to write io::Result::Ok(format!("{}", line?)) or to use an alternative that doesn't try to convert the error type, e.g.|line| line.to_string()).

Note: Typically I would recommend doing x.to_string() over format!("{}", x).

And why the error message is so strange ? Couldn't it be something like the Ok type and return type of ? don't match ?

In the original code I format multiple variables, but I totally forget to modify this

What is the error message?

Ah, I see it now. I mean, it could be improved, but it does say it here:

cannot infer type for type parameter `E` declared on the enum `Result`

The error message is guessing where you need an annotation. This is a case where the guess is wildly incorrect, I'm guessing because it doesn't properly account for closures.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.