9951 explained code solutions for 126 technologies


rustHow do I check the type of a variable in Rust?


You can check the type of a variable in Rust using the std::any::type_name function. This function takes a reference to a variable and returns a string containing the type of the variable.

let x = 5;
println!("x is of type {}", std::any::type_name::<&x>());

Output example

x is of type i32

The code above consists of the following parts:

  1. let x = 5; - This declares a variable x and assigns it the value 5.
  2. std::any::type_name::<&x>() - This is the function call to std::any::type_name which takes a reference to the variable x as an argument.
  3. println!("x is of type {}", std::any::type_name::<&x>()); - This prints the type of the variable x to the console.

Helpful links

Edit this code on GitHub