How to find variable type in Rust example
This tutorial shows how to get the variable datatype in Rust “Occasionally, it’s necessary to determine the variable type to validate assigned data.
Rust gets Variable Type
There are various ways to obtain the datatype of a variable in Rust:
Using the std::any::type_name function.
Using the std::intrinsics::type_name function.
std::any::type_name function to get type of variable:
The
std::any::type_name
function returns the type of a variable as a string slice.It is available in Rust standard library
std:any
that provides simple and readable methods to get the type of a variable. In the example below, the program prints the types of the following variables:- Integer types
- Boolean type
- String
- flat
- character
- tuples
- array
- vector
fn main() { let str = "test"; let number = 11; let price= 21.11; let f1: f32 = 12.01; let b = true; let charcter = 'z'; let tuptype: (i32, f64, u8) = (10, 2.9, 1); let arraytype = [1, 2, 3, 4, 5]; let vectortype = vec![1, 2, 3]; print_variable_type(&str); print_variable_type(&number); print_variable_type(&price); print_variable_type(&f1); print_variable_type(&b); print_variable_type(&charcter); print_variable_type(&tuptype); print_variable_type(&arraytype); print_variable_type(&vectortype); } fn print_variable_type<K>(_: &K) { println!("{}", std::any::type_name::<K>()) }
Output:
&str i32 f64 f32 bool char (i32, f64, u8) [i32; 5] alloc::vec::Vec<i32>
Using std::intrinsics::type_name Function:
Another approach to obtain the variable type is by using the
std::intrinsics::type_name
function. However, note that this function is part of an unstable feature and may not work in a stable release.#![feature(core_intrinsics)] fn main() { let str = "test"; let number = 11; let price= 21.11; let f1: f32 = 12.01; let b = true; let charcter = 'z'; let tuptype: (i32, f64, u8) = (10, 2.9, 1); let arraytype = [1, 2, 3, 4, 5]; let vectortype = vec![1, 2, 3]; print_variable_type(&str); print_variable_type(&number); print_variable_type(&price); print_variable_type(&f1); print_variable_type(&b); print_variable_type(&charcter); print_variable_type(&tuptype); print_variable_type(&arraytype); print_variable_type(&vectortype); } fn print_variable_type<K>(_: &K) { println!("{}", unsafe { std::intrinsics::type_name::<K>() }); }
Conclusion
In summary, understanding how to retrieve variable types in Rust is essential for developers to write efficient code. By utilizing these two methods, one can debug code effectively and prevent errors.