4

We may want to ensure two types are compatible, especially when writing macros. To check that two arguments are the same type for example.

How to best ensure types are compatible?


Similar to this C question, but for Rust.

Community
  • 1
  • 1
ideasman42
  • 42,413
  • 44
  • 197
  • 320

1 Answers1

5

A simple way to ensure types match is to assign them to a dummy value, within a block that never executes.

macro_rules! check_type_pair {
    ($a:expr, $b:expr) => {
        if false {
            let _type_check = if false {$a} else {$b};
        }
    }
}

Then within a macro you can simply add:

check_type_pair!($arg_1, $arg_2);

See example usage.

Community
  • 1
  • 1
ideasman42
  • 42,413
  • 44
  • 197
  • 320