I have this code.
if let Ok(file) = env::var("CONF") {
if let Ok(mut reader) = fs::File::open(&file) {
if let Ok(conf) = Json::from_reader(&mut reader) {
// do something with conf
}
}
}
I'm trying to make it less like a festive holiday tree and was thinking about chaining. Notice that each step in this chain produces another Result
, so clearly this won't work (we get Result
in Result
).
let conf = env::var("CONF")
.map(fs::File::open)
.map(Json::from_reader);
// do something with conf
Also my error types differ for each step, which means I can't just replace .map
with .and_then
.
I think I'm looking for something that is similar to JavaScript's promises. That is, a promise returned from inside a promise unwraps the inner promise. The signature should probably be along the lines of:
impl<T, E> Result<T, E> {
fn map_unwrap<F, U, D>(&self, op: F) -> Result<U, D>
where F: FnOnce(T) -> Result<U, D>
}
Is there such a mechanism in Rust? Is there another way to get rid of my festive holiday tree?