变量的寿命不够长:匹配选项类型

Variable does not live long enough: matching Option type

我正在使用 getopts,我之前从这样的标志中获取值:

let file = matches.opt_str("f").unwrap();
let file_path = Path::new(&file);

但是,我想通过将路径设为可选来更好地处理可能出现的错误。这是我的新代码:

let file = matches.opt_str("f");
let file_path = match file {
    Some(f) => Some(Path::new(&f)),
    None    => None
}

但是,当我尝试编译这段代码时,出现错误 'f' does not live long enough。我完全被难住了。

这是我的代码的 MCVE:

use std::path::Path;

fn main() {
    let foo = Some("success".to_string());
    let string = match foo {
        Some(s) => Some(Path::new(&s)),
        None    => None
    };
}
error[E0597]: `s` does not live long enough
 --> src/main.rs:6:35
  |
5 |     let string = match foo {
  |         ------ borrow later stored here
6 |         Some(s) => Some(Path::new(&s)),
  |                                   ^^ - `s` dropped here while still borrowed
  |                                   |
  |                                   borrowed value does not live long enough

出现此问题是因为您在与绑定 s(使用 按值绑定)。但是,由于在 match arm 之后没有使用 s,它会被丢弃并导致无效引用,因此它被阻止了。

相反,您可以按引用绑定:

let string = match foo {
    Some(ref s) => Some(Path::new(s)),
    None        => None,
};

您还可以使用 as_ref:

Option<T> 获得 Option<&T>
let string = match foo.as_ref() {
    Some(s) => Some(Path::new(s)),
    None    => None,
};

我可能会使用最后一个解决方案加上 map:

let string = foo.as_ref().map(Path::new);

在现代 Rust 中,您可以利用 匹配人体工程学 并匹配 &Option<T>:

let string = match &foo {
    Some(s) => Some(Path::new(s)),
    None    => None,
};

另请参阅: