Ben Chuanlong Du's Blog

It is never too late to learn.

Get Type Name of Variables in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips & Traps

In [2]:
std::any::type_name::<i32>()
Out[2]:
"i32"
In [3]:
std::any::type_name::<0>()
std::any::type_name::<0>()
                      ^ 
constant provided when a type was expected
In [4]:
use std::any::{Any, TypeId};
In [5]:
std::TypeId::of::<i32>()


consider importing one of these items
In [6]:
#![feature(type_name_of_val)]
use std::any::type_name_of_val;

let x = 1;
println!("{}", type_name_of_val(&x));
let y = 1.0;
println!("{}", type_name_of_val(&y));
#![feature(type_name_of_val)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
an inner attribute is not permitted in this context

use of unstable library feature 'type_name_of_val'
println!("{}", type_name_of_val(&x));
               ^^^^^^^^^^^^^^^^ 
use of unstable library feature 'type_name_of_val'
println!("{}", type_name_of_val(&y));
               ^^^^^^^^^^^^^^^^ 
use of unstable library feature 'type_name_of_val'
In [ ]:
align_of, 
align_of_val and 
size_of and size_of_val
In [ ]:
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>());
}


fn main() {
let x: &str = "abc";
    print_type_of(&x);          // prints "f64"
    print_type_of(&vec![1, 2, 4]);  // prints "std::vec::Vec<i32>"
    print_type_of(&"foo");          // prints "&str"
}

Use the typename crate

In [38]:
:dep typename = "0.1.2"
In [39]:
use typename::TypeName;
In [40]:
String::type_name()
Out[40]:
"std::string::String"
In [41]:
Vec::<i32>::type_name()
Out[41]:
"std::vec::Vec<i32>"
In [42]:
[0, 1, 2].type_name_of()
Out[42]:
"[i32; 3]"
In [ ]:

Comments