This is a very short card about a tiny function I still find useful. After a few hours of coding, I sometimes want Rust to tell me the concrete type of a value without making me hover through an IDE or deliberately provoke the compiler.
How can I print the concrete type of a Rust value?
The standard library already knows the type name. A generic helper can expose it.
Reveal the answer
Pass a reference into a generic function and print std::any::type_name::<T>().
The helper
use std::any::type_name;
fn what_type<T>(_: &T) {
println!("type is: {}", type_name::<T>());
}The argument gives Rust a concrete T. The function does not need the value itself, so the parameter is named _. type_name::<T>() returns the name of that type as a string slice.
Use it with a few values
fn main() {
let number = 3232;
let name = "Rahul".to_string();
let list_of_nums = vec![1, 2];
what_type(&number);
what_type(&name);
what_type(&list_of_nums);
}type is: i32
type is: alloc::string::String
type is: alloc::vec::Vec<i32>
Before I knew this helper, I sometimes used IDE introspection or deliberately assigned a value to () so the compiler would complain and reveal the real type. This is a little less silly.
What I keep in my head
type_name::<T>() is useful for debugging and learning. The exact string is intended for diagnostics, so I would not build program logic around its format.