How to print data types of variables in Rust

In this article, we are going to find out ways of how to print data types of variables in rust. In rust, we have different data types for variables and at run time if we want to know the data type of any variable then we can find it with the help std::any::type_name::().

Let us understand this with the help of a pour example where we are trying to find the datatype of different variables.

How do I find the type of a variable in Rust


In this example, we are going to take different types of data and at the time of initialization, we will use the let keyword. This keyword allows the compiler to decide what is the datatype based on the type of data that are assigned to this variable.

Rust Program to find datatype of variable

fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
	let str = "StringSample";
    let num = 54;
  	let k = 12.4;
  	let isok = true;
    let _vect = vec!(1, 2, 4);
   

    print_type_of(&str);   // &str
    print_type_of(&num);   // i32 (integer 32 bit)
    print_type_of(&k);     // f64 (float 64 bit)
    print_type_of(&isok);  // bool ( boolean)
    print_type_of(&_vect); // vector of i32
    
}

Output

rustc -o main main.rs
./main
&str
i32
f64
bool
alloc::vec::Vec<i32>