Function bpaf::choice

source ·
pub fn choice<T: 'static>(
    parsers: impl IntoIterator<Item = Box<dyn Parser<T>>>
) -> impl Parser<T>
Expand description

Choose between several parsers specified at runtime

You can use this function to create multiple parsers that produce the same type of value at a runtime and let bpaf to pick one that best fits best. This function is designed to work in Combinatoric API, but you can use it in Derive API with extern.


#[derive(Debug, Clone)]
pub struct Options {
    desert: Option<&'static str>,
}

pub fn options() -> OptionParser<Options> {
    let desert = ["apple", "banana", "orange", "grape", "strawberry"]
        .iter()
        .map(|name| {
            long(name)
                .help("Pick one of the options")
                .req_flag(*name)
                .boxed()
        });
    let desert = choice(desert).optional();
    construct!(Options { desert }).to_options()
}

fn main() {
    println!("{:?}", options().run())
}
Output

Here choice function is used to create an option for each possible desert item

$ app --help

Usage: app [--apple | --banana | --orange | --grape | --strawberry]

Available options:
--apple
Pick one of the options
--banana
Pick one of the options
--orange
Pick one of the options
--grape
Pick one of the options
--strawberry
Pick one of the options
-h, --help
Prints help information

User can pick any item

$ app --apple
Options { desert: Some("apple") }

Since parser consumes only one value you can’t specify multiple flags of the same type

$ app --orange --grape
Error: --grape cannot be used at the same time as --orange

And Parser::optional makes it so when value is not specified - None is produced instead

$ app
Options { desert: None }