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(())
}