Getting the Some out of Option

From time to time I want to extract a value out of an Option<> in a function that returns Result<> and bail on the None case. Because there's only one "legitimate" line of execution I don't want to have to scope the Some() case.

I've been doing either this:

  let cert_der;
  let peer_cert = tls_stream.get_mut().peer_certificate()?;
  if let Some(peer_cert) = peer_cert {
    cert_der = peer_cert.to_der()?;
  } else {
    // Peer didn't present a certificate -- abort
    return Err(Error::TLS("Didn't get a certificate from remote".to_owned()));
  }

.. or this:

    let peer = match shst.cert_peer.get(hash.as_slice()) {
      Some(peer) => peer,
      None => return Err(Error::NotFound("Peer certificate not found".to_owned()))
    };

Are there any other (read: better/more convenient) ways to do it?

You can also use ok_or_else with a question mark.

let peer = shst.cert_peer.get(hash.as_slice())
    .ok_or_else(|| Error::NotFound("Peer certificate not found".to_string()))?;
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.