Is there a way to avoid the double `unwrap()` in the below code?

Viewed 38

I'm new to Rust.

I'm using axum as router.

Is there a way to avoid the double unwrap() in the below code?

let cookies = req
  .headers()
  .get("Cookie")
  .map(|c| c.to_str().unwrap_or(""))
  .unwrap_or("");

I need cookies as String or &str or empty string if no cookies are present.

1 Answers

You can use Option::and_then with Result::ok:

let cookies = req
  .headers()
  .get("Cookie")
  .and_then(|c| c.to_str().ok())
  .unwrap_or("");

Option::and_then is a way to chain Options together. It will automatically unwrap the Option returned, if it is Some.

Result::ok is a way to convert a Result into an Option. If the Result is Ok(value), it will return Some(value), otherwise None.

Related