Skip to content

Instantly share code, notes, and snippets.

Created May 31, 2016 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/e32e5d58b5316989d55219aab68eba8f to your computer and use it in GitHub Desktop.
Save anonymous/e32e5d58b5316989d55219aab68eba8f to your computer and use it in GitHub Desktop.
#![allow(dead_code)]
struct CommandArg<'o> {
names: &'o [&'o str],
help_text: &'o str,
}
fn parse_args_and_run_etc(args: &[CommandArg]) {
print!("Usage: app thingy ");
for arg in args {
match arg.names.first() {
Some(n) => print!("{} <VALUE> ", n),
None => print!("<VALUE> "),
}
}
println!("");
}
pub fn hypothetical_subcommand() {
let path = CommandArg {
names: &["--path", "-p"],
help_text: "The directory in which to create the instance.",
};
let name = CommandArg { names: &[], help_text: "The name of the instance to create." };
parse_args_and_run_etc(&[path, name]);
}
fn main() {
hypothetical_subcommand();
}
@judofyr
Copy link

judofyr commented May 31, 2016

Here's a version with Cow:

#![allow(dead_code)]

use std::borrow::Cow;

struct CommandArg<'o> {
  names: &'o [&'o str],
  help_text: Cow<'o, str>
}

fn parse_args_and_run_etc(args: &[CommandArg]) {
  print!("Usage: app thingy ");

  for arg in args {
    match arg.names.first() {
      Some(n) => print!("{} <VALUE> ", n),
      None => print!("<VALUE> "),
    }
  }

  println!("");

  for arg in args {
      println!("{}", arg.help_text);
  }

}

pub fn hypothetical_subcommand() {
  let path = CommandArg {
    names: &["--path", "-p"],
    help_text: Cow::Borrowed("The directory in which to create the instance."),
  };

  let name = CommandArg { names: &[], help_text: Cow::Owned("The name of the instance to create.".to_string()) };

  parse_args_and_run_etc(&[path, name]);
}

fn main() {
  hypothetical_subcommand();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment