Crate parse_variants[][src]

Expand description

This crate allows us to parse tokens as one of the variants given by an enum. This is achieved by deriving the parse_variants::Parse trait on the enumeration which will in turn derive a syn::Parse implementation with the desired logic.


For a project, I was trying to parse tokens that could either be an integer literal or an identifier from a ParseBuffer. This inspired me to write a custom derive macro for these kinds of use cases. We can now write

enum Number {

and then use this type to parse either variant from a parse buffer like so:

// input : &ParseBuffer
let num : Number = input.parse()?;

Parsing will return the first variant that can be parsed from the contents of the parse buffer. If none of the variants can be parsed, a compile error is returned. We can use this in any context where we wish to parse this type. The custom derive macro can also be used on much more general enum types, enabling pretty powerful parsing of variant types.

See the macro documentation for more use cases and some caveats.

Derive Macros


A derive macro that allows us to parse a variant of an enumeration.