0

I am using clap.rs to parse command line arguments and I am struggling with lifetimes and borrowing with Strings:

fn get_build_tool_kind_argument<'a>(short_arg: &'a str, long_arg : &'a str) -> Arg<'a, 'a> {
    let argument_name = format!("{}_pouet", long_arg);

    Arg::with_name(&argument_name)
        .short(short_arg)
        .long(long_arg)
        .takes_value(false)
        .help("Configure elements for maven build tool")
}

To call the function, I do get_build_tool_kind_argument("m", "maven").

Here is the compilation error I get:

error[E0597]: `argument_name` does not live long enough
  --> src\main.rs:29:21
   |
29 |     Arg::with_name(&argument_name)
   |                     ^^^^^^^^^^^^^ borrowed value does not live long enough
...
34 | }

I have seen a lot of questions and documentation but none seem to apply in my case. I still have limited comprehension about lifetimes.

From what I see here, the borrowed formatted value I inject to my Arg name is freed at the end of the function, so it can't outlive it and be used when I call get_build_tool_kind_argument. I can't find a way to keep using the format! macro and solve my problem.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
matthieusb
  • 505
  • 1
  • 10
  • 34
  • 2
    I believe your question is answered by the answers of [Return local String as a slice (&str)](https://stackoverflow.com/q/29428227/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 11 '18 at 13:00
  • TL;DR: you **cannot** do this, `Arg` will never allow it. – Shepmaster Jul 11 '18 at 13:01
  • "in Rust it is impossible to return a reference pointing into local variables of the function". This answers my question pretty well indeed. Sorry for the duplicate. – matthieusb Jul 11 '18 at 13:04
  • Just to clarify, I can't do what I intend here unless I use a (dirty) static lifetime or if I return the value of the owned type ? – matthieusb Jul 11 '18 at 13:07
  • 1
    That is correct. If you are calling this function a "few" times, then leaking memory may be acceptable. Otherwise you need to restructure your code so that you call `format!` before this function and pass in a reference to the result. – Shepmaster Jul 11 '18 at 13:17
  • Ok I understand now. I'll probably be using another parsing library from now on, but I get it. Thanks a lot for your help. – matthieusb Jul 11 '18 at 13:21

0 Answers0