Extracting result from option

I have a Option<&git2::Commit>. I want to transform it to a Option<git2::Tree>. Commit has a tree method, so the first try is:

opt_commit.map(|x| x.tree())

But this doesn't work because tree doesn't return Tree directly, it returns a Result<git2::Tree, git2::Error>, so this expression produces a Option<Result<git2::Tree, git2::Error>> which is not what I want. So maybe try to use the ? operator:

opt_commit.map(|x| x.tree()?)

This doesn't work either because now the closure returns a Result, and map wants an option. I've looked at and_then, unwrap_or etc and nothing seems to fit. Is it idiomatic to manually write some match expressions or is there a better way?

opt_commit.map(|x| x.tree()).transpose()?;

(Edit: fixed link)


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.