Search code examples
rustclap

How to pass String as Into<Str> argument when using Clap?


I am trying to use clap to create a CLI application. A Command has a constructor like this:

impl Command {
    pub fn new(name: impl Into<Str>) -> Self {...}
}

But I need to pass there a name loaded from shared .so library. The only way I can use it is something like:

let mut registry = Registry::new();
registry.load("./libapp_addon_no1.so").ok();
registry.load("./libapp_addon_no2.so").ok();

for command in registry.commands() {
    // command.name is a String
    cli = cli.subcommand(Command::new(&*command.name.clone().leak()));
}

It works, but is there a better way to produce Into<Str> from a copy of String?


Solution

  • From Str:

    NOTE: To support dynamic values (i.e. String), enable the string feature

    You can use cargo to add the string feature:

    cargo add clap -F string
    

    Or you can edit Cargo.toml manually:

    [dependencies]
    clap = { version = "4.4.18", features = ["string"] }