One-liner to convert Result<Result<T, E>, E> to Result<T, E>

I want to reduce nesting level of the following code:

read(file)
        .map_err(|error| format!("cannot read file {:?}: {}", file, error))
        .and_then(|content| {
            String::from_utf8(content).map_err(|error| {
                format!(
                    "cannot convert content of file {:?} to UTF-8: {}",
                    file, error
                )
            })
        })

There is flatten, but it is still on the nightly.

2 Likes
res.unwrap_or_else(Err)
6 Likes

How about this?

fn flatten<T, E>(res: Result<Result<T, E>, E>) -> Result<T, E> {
    res.and_then(|x| x)
}