use clapcmd::{Arg, ArgMatches, ClapCmd, ClapCmdResult, Command}; #[derive(Clone)] struct State { counter: u32, } fn do_count(cmd: &mut ClapCmd, matches: ArgMatches) -> ClapCmdResult { let num: u32 = *matches.get_one("num").expect("num is required"); let state = cmd.get_state().ok_or("state missing")?; let new_count = state.counter + num; cmd.info(format!("count is now: {}", new_count)); cmd.set_state(State { counter: new_count }); Ok(()) } fn do_speak(cmd: &mut ClapCmd, matches: ArgMatches) -> ClapCmdResult { let animal: &String = matches.get_one("animal").expect("animal is required"); match animal.as_str() { "cat" => cmd.output("meow"), "dog" => cmd.output("woof"), _ => unreachable!(), } Ok(()) } fn main() { let mut cmd = ClapCmd::with_state(State { counter: 0 }); cmd.add_command( do_count, Command::new("count").about("increment a counter").arg( Arg::new("num") .short('n') .long("num") .help("number to increment counter by") .value_parser(clap::value_parser!(u32).range(..100)) .default_value("1"), ), ); cmd.add_command( do_speak, Command::new("speak").about("say an animal sound").arg( Arg::new("animal") .short('a') .long("animal") .help("which animal to say") .value_parser(["cat", "dog"]) .required(true), ), ); cmd.run_loop(); }