为什么这个变量存活时间不够长?

3

我将尝试从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()或其他任何方法,这种情况都会发生。
1个回答

4

由于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 的期望太过愚蠢了。 - Camden Narzt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接