Instead of remembering the specific type names for Rust punctuation, keywords, and delimiters, use the Token! macro. This macro expands to the correct token type.
As a Type
Use Token![...] in struct fields or for type annotations in parse methods.
As an Expression
Use Token![...] to:
- Peek:
input.peek(Token![...]) - Parse:
input.parse::<Token![...]>()? - Construct:
let the_token = Token; (where span is a proc_macro2::Span) - Print: Use with the
quote! macro: quote!(... #the_token ...)
use syn::{Ident, Token};
use syn::parse::{Parse, ParseStream, Result};
// Example: Using Token! in a struct and parsing
pub struct UnitStruct {
struct_token: Token![struct],
ident: Ident,
semi_token: Token![;],
}
impl Parse for UnitStruct {
fn parse(input: ParseStream) -> Result<Self> {
let struct_token: Token![struct] = input.parse()?;
let ident: Ident = input.parse()?;
let semi_token = input.parse::<Token![;]>()?;
Ok(UnitStruct {
struct_token,
ident,
semi_token,
})
}
}
// Example: Using Token! for peeking and construction
fn make_unit_struct(name: Ident) -> UnitStruct {
let span = name.span();
UnitStruct {
struct_token: Token,
ident: name,
semi_token: Token,
}
}
fn check_struct(input: &ParseStream) -> bool {
input.peek(Token![struct])
}