I would like to be able to use the value of a variable (or better yet, the return of a function(arg)
) as the about string for a CLI program defined using structopt. The end goal is a fully localized CLI that detects the system language or an ENV var and loads up localized strings that get baked into the --help
message, etc.
By default it uses the documentation comment:
/// My about string
#[derive(StructOpt)]
struct Cli {}
I've found I can pass a manually entered string instead:
#[derive(StructOpt)]
#[structopt(about = "My about string")]
struct Cli {}
That's one step closer, but what I really want to do is pass a variable:
let about: &str = "My about string";
#[derive(StructOpt)]
#[structopt(about = var!(about))]
struct Cli {}
That last block is pseudo-code because I don't know what syntax to use to achieve this. In the end, I'll need more than just a single string slice, but I figured that was a place to start.
How can I pass through values like this to structopt? Do I need to access the underlying clap interfaces somehow?
StructOpt just adds a derive macro and a corresponding trait over clap. The clap crate has a function to set the about message at runtime , so we just need to add that. If we look athow from_args
works we can see that it creates the clap App
struct before turning it into the user-defined struct.
Thus, to do what you want:
use structopt::StructOpt;
fn get_localized_about() -> &'static str {
"localized string"
}
#[derive(Debug, StructOpt)]
struct Foo {}
fn main() {
let foo = Foo::from_clap(&Foo::clap().about(get_localized_about()).get_matches());
println!("{:#?}", foo);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.