3

我正在尝试从中提取一个可选的 arg 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()任何其他我想尝试的东西都会发生这种情况。

4

1 回答 1

4

因为Path::new(&x)返回一个&Path借用它的内容的x.

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

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

let cfgFilePath = match matches.opt_str("c") {
    Some(s) => Some(PathBuf::from(s)),
    None => None
};
于 2015-12-25T04:35:10.837 回答