Macro_rules: variable 'opcode_value' is still repeating at this depth

In my macro I want to return struct that will return a $opcode_value that I passed to macro, but I got an error:

error: variable 'opcode_value' is still repeating at this depth
  --> src/main.rs:20:17
   |
20 |                 $opcode_value
   |                 ^^^^^^^^^^^^^

error: could not compile `playground` due to previous error

this is my code:

macro_rules! packet {
    (
        properties {
            $(opcode $opcode_value:expr;)?
        }
        
        $(#[$outer:meta])*
        $vis:vis struct $PacketStruct:ident {
            $($field_name:ident: $field_type:ty),*$(,)?
        }
    ) => {
        $(#[$outer])*
        #[derive(Clone)]
        $vis struct $PacketStruct {
            $($field_name: $field_type),*
        }
        
        impl $PacketStruct {
            pub fn get_opcode() -> u32 {
                $opcode_value
            }
        }
    };
}


fn main() {
    packet! {
        properties {
            opcode 10;
        }
        
        #[derive(Hash)]
        pub struct Outcome {
            name: String,
            os: u8,
            game_name: String,
        }
    }
}

this is sandbox.

Could somebody explain how to fix this issue ? And also, how to set return type of get_opcode according to type of $opcode_value ?

Solved by adding ? to impl body:

$(
	impl $PacketStruct {
		pub fn get_opcode() -> u32 {
			$opcode_value
		}
	}
)?

but question how to get $opcode_value type still opened

It's not possible for a macro to figure out the type of an expression. You'll have to take the type as input or hardcode a specific one like in the post you marked as a solution.

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.