How to parse a keyword with syn?

The documentation of Ident says: »A word of Rust code, which may be a keyword or legal variable name.« But parsing a keyword fails: println!("{:?}", syn::parse_str::<syn::Ident>("struct"));

How can I parse a word (keyword or variable name) with syn?

The documentation also says

An identifier constructed with Ident::new is permitted to be a Rust keyword, though parsing one through its Parse implementation rejects Rust keywords. Use input.call(Ident::parse_any) when parsing to match the behaviour of Ident::new .

So here’s a code example that works

use syn::ext::IdentExt;
use syn::parse::Parser;
use syn::Ident;

fn main() {
    dbg!(Ident::parse_any.parse_str("struct"));
}

Stupid me. I haven't realized this part.

And together with Ident::peek_any it works.

let lookahead = input.lookahead1();
if lookahead.peek(Ident::peek_any) {
    input.call(Ident::parse_any)?
} …

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.