简体   繁体   中英

Rust - How to reference T value inside Option<T>

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 ?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM