Skip to main content

find_subcommand

Function find_subcommand 

Source
pub const fn find_subcommand<'a>(
    subcommands: &'a [&'a Command<'a>],
    name: &str,
) -> &'a Command<'a>
Expand description

Resolve a subcommand by name or alias, at compile time.

For Command::default_subcommand, which names a command that a derive cannot see: the variants of a subcommand enum are a different macro expansion, so the name is all the parent has. Searching the list in a const fn closes that gap — the answer is the same &'static the table already holds, found before the program runs.

A name no subcommand answers to is a compile error, since this panics during const evaluation. That is the whole point of doing it here rather than at startup.

use usage_argv::{find_subcommand, Command};

static RUN: Command = Command { name: "run", ..Command::EMPTY };
static SUBS: &[&Command] = &[&RUN];
static ROOT: Command = Command {
    name: "ex",
    subcommands: SUBS,
    default_subcommand: Some(find_subcommand(SUBS, "run")),
    ..Command::EMPTY
};
assert_eq!(ROOT.default_subcommand.unwrap().name, "run");