Function combine::choice

source ·
pub fn choice<Input, P>(ps: P) -> Choice<P>
where Input: Stream, P: ChoiceParser<Input>,
Expand description

Takes a tuple, a slice or an array of parsers and tries to apply them each in order. Fails if all the parsers fails or if an applied parser consumes input before failing.

// `choice` is overloaded on tuples so that different types of parsers can be used
// (each parser must still have the same input and output types)
let mut parser = choice((
    string("Apple").map(|s| s.to_string()),
    many1(digit()),
    string("Orange").map(|s| s.to_string()),
));
assert_eq!(parser.parse("1234"), Ok(("1234".to_string(), "")));
assert_eq!(parser.parse("Orangexx"), Ok(("Orange".to_string(), "xx")));
assert!(parser.parse("Appl").is_err());
assert!(parser.parse("Pear").is_err());

// If arrays or slices are used then all parsers must have the same type
// (`string` in this case)
let mut parser2 = choice([string("one"), string("two"), string("three")]);
// Fails as the parser for "two" consumes the first 't' before failing
assert!(parser2.parse("three").is_err());

// Use 'attempt' to make failing parsers always act as if they have not committed any input
let mut parser3 = choice([attempt(string("one")), attempt(string("two")), attempt(string("three"))]);
assert_eq!(parser3.parse("three"), Ok(("three", "")));