【问题标题】:why doesn't this variable live long enough?为什么这个变量的寿命不够长?
【发布时间】:2016-03-31 07:48:04
【问题描述】:

我正在尝试从getopts 中提取一个可选参数,并且对于变量s,获取一个借用的值并不会存在足够长的错误。

代码:

let cfgFilePath = match matches.opt_str("c") {
    Some(s) => Some(Path::new(&s.clone())),
    None => None
};

错误:

main.rs:29:36: 29:45 error: borrowed value does not live long enough
main.rs:29         Some(s) => Some(Path::new(&s.clone())),
                                              ^~~~~~~~~
main.rs:31:7: 65:2 note: reference must be valid for the block suffix following statement 10 at 31:6...
main.rs:31     };
main.rs:32     let tmpdir = Path::new(&matches.opt_str("t").unwrap_or("/tmp/".to_string()));
main.rs:33     let name = matches.opt_str("n").unwrap_or_else(||{
main.rs:34         print_usage(&program, opts);
main.rs:35         panic!("error: -n NAME required");
main.rs:36     });
           ...

无论.clone().to_owned().to_str() 或其他任何我想尝试的东西,都会发生这种情况。

【问题讨论】:

    标签: rust ownership borrow-checker


    【解决方案1】:

    因为Path::new(&x) 返回的&Path 借用了x 的内容。

    Some(s) => Some(Path::new(&s.clone())), // Type is Option<&Path>
    // reborrow --------------^
    

    您真正想要做的是使用PathBuf(拥有的等同于Path)。 PathBuf 将获得 s 的所有权,而不是借用它。

    let cfgFilePath = match matches.opt_str("c") {
        Some(s) => Some(PathBuf::from(s)),
        None => None
    };
    

    【讨论】:

    • 哦,好吧,这取决于我对 Path::new 会为我做什么的愚蠢期望。
    猜你喜欢
    • 2016-01-22
    • 2018-12-20
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2017-10-16
    • 2015-12-05
    相关资源
    最近更新 更多