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); 
3
  • 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 ? Commented Jul 17, 2019 at 5: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)? Commented Jul 17, 2019 at 6:31
  • 2
    Possible duplicate of How do I print the type of a variable in Rust? Commented Jul 17, 2019 at 7:13

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.