Home > Software design >  Rust - How to reference T value inside Option<T>
Rust - How to reference T value inside Option<T>

Time:06-03

fn main() {
    let float = 1.0;

    let var: &f64 =  {
        let inner_option = Some(float);

        inner_option.as_ref().unwrap()
    };

    dbg!(var);
}

You get this error

error[E0597]: `inner_option` does not live long enough
 --> src/main.rs:7:9
  |
4 |     let var: &f64 =  {
  |         --- borrow later stored here
...
7 |         inner_option.as_ref().unwrap()
  |         ^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
8 |     };
  |     - `inner_option` dropped here while still borrowed


How do I get a reference to the longer living float variable while accessing it from the Option inner_option?

CodePudding user response:

Calling Some(float) will copy the float making a Option<f64> which will be destroyed at the end of that scope, and would leave the reference invalid.

If you were to instead make an Option<&f64> that only references float, then it would work:

fn main() {
    let float = 1.0;

    let var: &f64 =  {
        let inner_option = Some(&float);

        inner_option.unwrap()
    };

    dbg!(var);
}
  • Related