1

Is it possible to get static lifetimes from Clap's arg parser?

let args = App::new(env!("CARGO_PKG_NAME"))
      .version(env!("CARGO_PKG_VERSION"))
      .author(env!("CARGO_PKG_AUTHORS"))
      .about(env!("CARGO_PKG_DESCRIPTION"))
      .bin_name(env!("CARGO_PKG_NAME"))
      .arg(
        Arg::with_name("db-name")
          .short("d")
          .long("db-name")
          .value_name("NAME")
          .help("Sets database name")
          .takes_value(true),
      )
      .get_matches();

let db_name = args.value_of(val)?; // <-- want as &'static str

Currently getting them as &str. The end goal is to have a single config object that lasts for the lifetime of the program. I don't really want to copy the values around either, just to remain in a single location.

Will Squire
  • 6,127
  • 7
  • 45
  • 57
  • 2
    Ask yourself: what does `'static` mean. Is it possible to create a `'static` lifetime during runtime? – hellow May 02 '19 at 11:50
  • I have and the answer is yes because I know there's a lazy_static crate :) but I'm not familiar with it so would want to know if there's better ways of achieving this? – Will Squire May 02 '19 at 12:01
  • You must leak memory to do that. Check my proposed duplicate. – Boiethios May 02 '19 at 12:01
  • Thanks French, it's similar for sure but mines aimed at the Clap crate in particular. I thought there might be a way to request it as `static` via that crate's API. I know lazy_static exists, but thought there might be a solution available without needing another crate. – Will Squire May 02 '19 at 12:17
  • @willsquire Clap builds this string at runtime, thus it won't leak any memory behind your back to give you a static string. – Boiethios May 02 '19 at 12:28
  • 1
    At your place, I wouldn't leak the memory if you have a lot of configuration. I would create a struct with the configuration and pass it to every function that needs it. – Boiethios May 02 '19 at 12:35
  • I have, see: https://github.com/WillSquire/Graphy/blob/master/api/src/main.rs and https://github.com/WillSquire/Graphy/blob/master/api/src/config/mod.rs. But it needs thread safety and I want to pass a ref to everything that needs it rather than copy. I'm open to ideas? :) – Will Squire May 02 '19 at 12:40
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/192723/discussion-between-french-boiethios-and-willsquire). – Boiethios May 02 '19 at 12:55

0 Answers0