Reputation: 2003
I'm trying to extract an optional arg from getopts
, and getting a borrowed value doesn't live long enough error for the variable s
.
code:
let cfgFilePath = match matches.opt_str("c") {
Some(s) => Some(Path::new(&s.clone())),
None => None
};
error:
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 });
...
This happens regardless of .clone()
, .to_owned()
, .to_str()
or anything else I've thought to try.
Upvotes: 3
Views: 175
Reputation: 5780
Because Path::new(&x)
returns an &Path
that borrows it's contents from x
.
Some(s) => Some(Path::new(&s.clone())), // Type is Option<&Path>
// reborrow --------------^
What you actually want to do is use a PathBuf
(the owned equivalent of Path
). PathBuf
will take ownership of s
instead of borrowing it.
let cfgFilePath = match matches.opt_str("c") {
Some(s) => Some(PathBuf::from(s)),
None => None
};
Upvotes: 5