Static Type Names With std::any::type_name

Print readable type names with std::any::type_name for generics and nested containers, keeping the output strictly for diagnostics.

RustData Integrity

Code

rustsnippet
25 lines
use std::any::type_name;

fn describe<T>(_value: &T) -> &'static str {
    // 返回编译器生成的类型名,仅供调试展示
    type_name::<T>()
}

fn main() {
    println!("u32 -> {}", describe(&1u32));
    println!("String -> {}", describe(&String::from("x")));
    println!("Vec<u8> -> {}", describe(&vec![0u8; 3]));

    // 引用、切片与 Option 的组合会被完整展开
    let slice: &[i64] = &[1, 2, 3];
    println!("slice -> {}", describe(&slice));
    println!("option -> {}", describe(&Some(3.5f64)));

    // 嵌套容器与元组的类型名保留结构信息
    let nested = vec![Some(("id", 7u16))];
    println!("nested -> {}", describe(&nested));

    // 与 size_of 搭配可快速核对泛型实例
    println!("size of Vec<u8>: {}", std::mem::size_of::<Vec<u8>>());
    println!("size of u8 slice ptr: {}", std::mem::size_of::<&[u8]>());
}

How it works

Static Type Names With std::any::type_name keeps everything in the functions describe and main.

Using it

The run emits 8 labeled sections — u32 ->, String ->, Vec<u8> ->, slice ->, option ->, nested ->, size of Vec<u8>:, size of u8 slice ptr: — one per step.

main is the driver: it invokes describe before returning.

Key statements

fn describe<T>(_value: &T) -> &'static str {
    // 返回编译器生成的类型名,仅供调试展示
    type_name::<T>()
}
let nested = vec![Some(("id", 7u16))];

Interactive Tools for This Topic

FAQ

What does Static Type Names With std::any::type_name print when run?
Execute the whole file; each printed line is prefixed with a label like `u32 ->`, `String ->`, `Vec<u8> ->`.