1
macro_rules! print_entity {
    ($x: expr) => {
        {
            println!("Object type: {}\nDeclared name: {}\n")
        }
    }
}

For reference of definition, consider:

let the_foo: MyBar = MyBar::new();

In the case of the macro above, the "Declared name" value should equal the_foo. The struct type should equal TheBar. How can this be done?

print_entity!(the_foo);
Thomas Braun
  • 505
  • 3
  • 14
  • 1
    To get the variable name (i.e. `the_foo`) is easy. To get the type would probably be best achieved by declaring a trait, similar to `Debug` and implementing it. Are you after something like the `dbg!` macro ? – Denys Séguret Jul 17 '19 at 05:29
  • 1
    A macro parameter of type `expr` can take arbitrary expressions. What is the declared name in `print_entity!(some_var + 100 * another_var)`? – Sebastian Redl Jul 17 '19 at 06:31
  • 2
    Possible duplicate of [How do I print the type of a variable in Rust?](https://stackoverflow.com/questions/21747136/how-do-i-print-the-type-of-a-variable-in-rust) – hellow Jul 17 '19 at 07:13

1 Answers1

2

If you only need that for debugging, you can get the compiler to print an error message with the type like this:

let foo: () = 1i32;

which gives the following error:

error[E0308]: mismatched types
  --> src/main.rs:24:15
   |
24 | let foo: () = 1i32;
   |               ^^^^ expected (), found i32
   |
   = note: expected type `()`
              found type `i32`

Or, building on @Denys Séguret's comment, you need to define a trait and implement it for every type you may want to print (this can be made easier with a macro too):

trait TypeToStr {
    fn get_type_str (&self) -> &'static str;
}

macro_rules! impl_type_to_str {
    ($($T: ty),+) => {
        $(
        impl TypeToStr for $T {
            fn get_type_str (&self) -> &'static str { stringify!($T) }
        }
        )*
    }
}

impl_type_to_str!(i32, f64);

macro_rules! print_type {
    ($e: expr) => {
        println!("{} has type {}", stringify!($e), $e.get_type_str());
    }
}

fn main() {
    print_type!(1i32);
    print_type!(3.14f64);
}

playground

Jmb
  • 18,893
  • 2
  • 28
  • 55