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