How do you deal with an Option in the case that you already know that it's Some?

45 points R4z0rw1r3z

So, I've come to understand that .unwrap() is 'almost always a bad way to deal with Options', but I'm curious as to how you deal with options that will always be Some.

For instance, the Number Variant for serde\_json::Value has a as_f64(&self) -> Option<f64> which looks like it could return None, but when looking at the implementation it can only return Some.

 pub fn as_f64(&self) -> Option<f64> {
   match self.n {
       N::PosInt(n) => Some(n as f64),
       N::NegInt(n) => Some(n as f64),
       N::Float(n) => Some(n),
   }
}

So more to my question, how would you convert Number to f64 in this contrived example. I've come up with a few ways, but it feels as if there should be a better way to deal with options when you already know that it will be Some.

fn ensure_f64(n: &Number) -> f64 {
    n.as_f64().unwrap()
}

fn ensure_f64(n: &Number) -> f64 {
    n.as_f64().unwrap_or_default()
}

fn ensure_f64(n: &Number) -> f64 {
    match n.as_f64() {
        Some(f) => f,
        None => 0.00
    }
}

Reading back my question it kinda feels like a 'How can I make the compiler understand that I know better'- question.

But I assure you it really isn't, I'm genuinely curious if there is a better way to deal with this that I'm not aware of.

EDIT: Thanks a lot guys, consider my curiosity satified!