I'm currently trying to write a little command line app in Rust and I've hit a wall with lifetimes.
extern crate clap;
use self::clap::{App, Arg};
use std::env;
impl<'p> Params<'p> {
fn get_username_arg<'r>() -> Arg<'r, 'r> {
let mut arg = Arg::with_name("Username")
.short("u")
.long("username")
.takes_value(true);
match env::var("USERNAME") {
Ok(username) => {
// How do I pass `username` to default_value?
arg.default_value(username)
}
Err(e) => arg.required(true),
}
}
// More code below...
}
The problem is that I'm trying to pass username
to the default value method, which requires a str
with a lifetime of 'r
. I tried cloning but I can't figure how to tell it what the lifetime of the clone is going to be. I tried something along the following lines:
let cln = (&*username).clone::<'r>();
arg.default_value(username)
For some reason its now telling me that username
doesn't live long enough, even though it shouldn't matter since I cloned the data.
So my question is, how do I make this compile?
EDIT: I'd like to add that its important to me that the signature stays the same aside from the lifetime parameters. I don't mind doing expensive operations such as cloning to make this work.
clone
in this case has a signature of<'s>clone() -> &'s str
if you remove elisions(and reifySelf
) according to my very limited understanding of Rust in general. So if I clone withclone::<'r>()
it should force the lifetime... – Barthelemy