Why this usage of as works?

i was watching the source code of strum lib and wondering why this usage of as doesn't have any problem but when i try to use it will go wrong?

#[proc_macro_derive(EnumString, attributes(strum))]
pub fn from_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = syn::parse_macro_input!(input as DeriveInput);

    let toks =
        macros::from_string::from_string_inner(&ast).unwrap_or_else(|err| err.to_compile_error());
    debug_print_generated(&ast, &toks);
    toks.into()
}

This is specific to the syn::parse_macro_input! macro.

Can you give an example of where it “goes wrong”? It won’t work the same outside of that macro.

A macro can take arbitrary input that's lexically valid Rust, and transform it into actual, semantically valid Rust. The parse_derive_input!() macro pattern matches on $expr as $type and emits code that parses the passed token stream as the specified type.

1 Like

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.