Function combine::choice [] [src]

pub fn choice<S, P>(ps: S) -> Choice<S, P> where
    S: AsMut<[P]>,
    P: Parser

Takes 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.

let mut parser = choice([string("Apple"), string("Banana"), string("Orange")]);
assert_eq!(parser.parse("Banana"), Ok(("Banana", "")));
assert_eq!(parser.parse("Orangexx"), Ok(("Orange", "xx")));
assert!(parser.parse("Appl").is_err());
assert!(parser.parse("Pear").is_err());

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 'try' to make failing parsers always act as if they have not consumed any input
let mut parser3 = choice([try(string("one")), try(string("two")), try(string("three"))]);
assert_eq!(parser3.parse("three"), Ok(("three", "")));