【问题标题】:Variable does not live long enough: matching Option type变量的寿命不够长:匹配选项类型
【发布时间】:2015-12-05 20:30:24
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: rust lifetime


    【解决方案1】:

    出现问题是因为您在与绑定 s(使用 bind-by-value )。但是,由于在匹配臂之后没有使用s,它会被丢弃并导致无效引用,因此它被阻止了。

    相反,您可以按引用绑定

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

    您还可以使用as_refOption<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,
    };
    

    另见:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 2016-01-22
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多