How to find variable type in Rust example
This tutorial shows how to get the variable datatype in Rust
Rust gets Variable Type
There are multiple ways to get variable types
- use
std::any::type_name
function - use
std::intrinsics::type_name
std::any::type_name function to get type of variable:
std::any::type_name function
returns type of variable and return string slice value.
The below example program get printing the variable type of
- 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>
std::intrinsics::type_name function:
This is another way to get a variable type,
std::intrinsics::type_name
is an unstable feature that should 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>() });
}