Search code examples
rustrust-axum

How to avoid the double `unwrap()` when getting a string from headers?


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'm using the axum crate, so req is a RequestParts.

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


Solution

  • 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.