Rust - 如何在 Option<T> 中引用 T 值

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

你收到这个错误

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


如何在从选项 inner_option 访问时获得对寿命更长的 float 变量的引用?

调用 Some(float) 复制 float 制作一个 Option<f64> ,它将在该范围的末尾被销毁,并离开引用无效。

如果您改为制作一个仅 引用 floatOption<&f64>,那么它将起作用:

fn main() {
    let float = 1.0;

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

        inner_option.unwrap()
    };

    dbg!(var);
}