帮我将下面用到 clap库的 rust 代码改为 宏版本代码 use clap::{App, AppSettings, Arg, SubCommand}; use…
- User
帮我将下面用到 clap库的 rust 代码改为 宏版本代码 use clap::{App, AppSettings, Arg, SubCommand}; use std::process::exit;
fn main() { let matches = App::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .setting(AppSettings::DisableHelpSubcommand) .setting(AppSettings::SubcommandRequiredElseHelp) .setting(AppSettings::VersionlessSubcommands) .subcommand( SubCommand::with_name("set") .about("Set the value of a string key to a string") .arg(Arg::with_name("KEY").help("A string key").required(true)) .arg( Arg::with_name("VALUE") .help("The string value of the key") .required(true), ), ) .subcommand( SubCommand::with_name("get") .about("Get the string value of a given string key") .arg(Arg::with_name("KEY").help("A string key").required(true)), ) .subcommand( SubCommand::with_name("rm") .about("Remove a given key") .arg(Arg::with_name("KEY").help("A string key").required(true)), ) .get_matches();
match matches.subcommand() { ("set", Some(_matches)) => { eprintln!("unimplemented"); exit(1); } ("get", Some(_matches)) => { eprintln!("unimplemented"); exit(1); } ("rm", Some(_matches)) => { eprintln!("unimplemented"); exit(1); } _ => unreachable!(), }}
- Assistant
下面是使用宏版本的代码:
use clap::*; macro_rules! build_app { () => { App::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .setting(AppSettings::DisableHelpSubcommand) .setting(AppSettings::SubcommandRequiredElseHelp) .setting(AppSettings::VersionlessSubcommands) }; } fn main() { let matches = build_app!() .subcommand( SubCommand::with_name("set") .about("Set the value of a string key to a string") .arg(Arg::with_name("KEY").help("A string key").required(true)) .arg( Arg::with_name("VALUE") .help("The string value of the key") .required(true), ), ) .subcommand( SubCommand::with_name("get") .about("Get the string value of a given string key") .arg(Arg::with_name("KEY").help("A string key").required(true)), ) .subcommand( SubCommand::with_name("rm") .about("Remove a given key") .arg(Arg::with_name("KEY").help("A string key").required(true)), ) .get_matches(); match matches.subcommand() { ("set", Some(_matches)) => { eprintln!("unimplemented"); exit(1); } ("get", Some(_matches)) => { eprintln!("unimplemented"); exit(1); } ("rm", Some(_matches)) => { eprintln!("unimplemented"); exit(1); } _ => unreachable!(), } }请注意,宏版本的代码与使用
clap库的原始代码之间没有实际区别,只是将创建 App 的代码通过宏build_app!进行了封装。这样做是为了让代码更加简洁和可读。