简体   繁体   中英

How to assert type in a Rust macro?

I created a macro function my_macro :

macro_rules! my_macro {
    ($param1:expr, $param2:expr) => {
        // ...
    };
}

How is it possible to assert that $param1 is the type MyType ? Is it possible to check for something more complex like Box<T> ? Or even the return type?

I've found assert_type_eq , but the documentation about it is confusing, and I don't see how to use it. Or if it is the best approach for the task.

I would like to add these type assertions to my macro, to make it easier to find out if it is used incorrectly.

Assign it to an explicitly typed variable:

macro_rules! my_macro {
    ($param1:expr, $param2:expr) => {
        {
            let param1: u64 = $param1; // compiling will throw an error
                                       // if the result isn't a u64
            let param2: u64 = $param2;
            
            param1 + param2
        }
    };
}

This also has the benefit of ensuring that the $param1 expression is only evaluated once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM