Unpacking in closure

This is somewhat similar to Using ? inside closure to return Result. I can't figure out how to get rid of the expect at label 'b- and use ? instead like at label ’a:

use anyhow::Result;
use std::{
    collections::HashMap,
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};      
#[allow(unused_labels)]
fn main() -> Result<()> {
    let path = Path::new("faust.txt");
    'a: {
        let file = File::open(&path)?;
        let reader = BufReader::new(file);
        let mut hash: HashMap<usize, String> = HashMap::new();
        for (k, v) in reader.lines().enumerate() {
            hash.insert(k, v?);
        }
        // dbg!(hash);                                                                           
    }
   'b: {
        let file = File::open(&path)?;
        let reader = BufReader::new(file);
        let hash: HashMap<usize, String> = reader
            .lines()
            .enumerate()
            .map(|(k, v)|{
                 (k, v.expect("some line"))
            })
            .collect();
        // dbg!(hash);                                                                           
    }
    Ok(())
}    

If you can collect T into a Collection<..>, you can collect Result<T, E> into a Result<Collection<..>, E>. You can use this to get the Result out of the closure, where ? can be used.

             .map(|(k, v)|{
-                 (k, v.expect("some line"))
+                 v.map(|v| (k, v))
             })
-            .collect();
+            .collect::<Result<_, _>>()?;
1 Like

Very nice! Thanks.