1

I'm learning Rust and I am struggling with optional URL parsing, I've got the following code:

use hyper::Uri; fn main() -> Result<(), String> { let url = Some("http://www.stackoverflow.com"); let works = if let Some(url) = url { Some(parse_url(url)?) } else { None }; let does_not = url.map(|u| parse_url(u)?); Ok(()) } fn parse_url(url_str: &str) -> Result<Uri, String> { unimplemented!(); } 

Rust playground link

Documentation says that calling ? can be used as a syntactic sugar to simplify error handling.

So what bothers me is that I can perfectly fine map the inner value of Option<T> manually, using if let syntax and return early from the method but cannot just .map() the inner value of Option<T>.

So my question is actually how can I easily parse an optional value by avoiding if/else conditions in Rust?

1 Answer 1

3

? handles errors in the current function. When you call map, you create a closure (using |_|), which is a different function.

You'd have to use ? outside of that closure:

let does_not = url.map(|u| parse_url(u))?; 

Unfortunately, this won't quite work as at this point you have a Option<Result<_, _>> rather than a Result<Option<T>, _>. You can fix that using transpose:

let does_not = url.map(|u| parse_url(u)).transpose()?; 

(Permalink to the playground)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.