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.
Code
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
CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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> ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.