Little A
Little A

Reputation: 7

What does ($tokenstream:ident as $ty:ty) mean in Rust

I'm trying to learn Rust, and want to understand everything in this code block.

#[macro_export(local_inner_macros)]
macro_rules! parse_macro_input {
    ($tokenstream:ident as $ty:ty) => {
        match $crate::parse_macro_input::parse::<$ty>($tokenstream) {
            $crate::export::Ok(data) => data,
            $crate::export::Err(err) => {
                return $crate::export::TokenStream::from(err.to_compile_error());
            }
        }
    };
    ($tokenstream:ident) => {
        parse_macro_input!($tokenstream as _)
    };
} 

My current issue is with ($tokenstream:ident as $ty:ty).

  1. What is the point of having dollar signs in front of the name for parameters in macro_rules? Does it have any functional purpose?
  2. What does the line of code mean? The way I read it is, "use parameter tokenstream of type ident as ty of type ty", and it doesn't make sense to me.

Thank you

Upvotes: 0

Views: 504

Answers (1)

ThoPaz
ThoPaz

Reputation: 174

  1. The dollar signs in a rust macro signal a "metavariable" and the part after the colon is called "fragment specifier". $foo:ty is for a type, $bar:ident is for an identifier, more details can be found here.
  2. Since you seem to be interested in the learning rather then just the solution, I'd recommend you to continue reading "Macros by Example". After going through that, you can probably answer that question 2 for yourself and everybody here. ;)

Upvotes: 1

Related Questions