TypeId Runtime Type Registry
Key a handler registry by std::any::TypeId so dispatch on Any values happens without matching every concrete type by hand.
Code
use std::any::{Any, TypeId};
use std::collections::HashMap;
fn describe(value: &dyn Any) -> &'static str {
// type_id 给出运行期类型标识:同类型恒等,跨类型不等
if value.type_id() == TypeId::of::<u32>() {
"unsigned 32-bit"
} else if value.type_id() == TypeId::of::<String>() {
"owned string"
} else {
"unrecognized"
}
}
fn main() {
println!("{}", describe(&7u32));
println!("{}", describe(&String::from("x")));
println!("{}", describe(&7u64));
// TypeId 实现 Hash + Eq:可直接作为类型注册表的键
let mut handlers: HashMap<TypeId, &str> = HashMap::new();
handlers.insert(TypeId::of::<u32>(), "handle_u32");
handlers.insert(TypeId::of::<String>(), "handle_string");
let payloads: Vec<Box<dyn Any>> = vec![Box::new(1u32), Box::new(String::from("text"))];
for value in &payloads {
let name = handlers.get(&value.type_id()).copied().unwrap_or("missing");
println!("dispatch -> {name}");
}
// 泛型类型按实参区分:Vec<u8> 与 Vec<String> 不是同一个 TypeId
println!(
"vec<u8> == vec<string>: {}",
TypeId::of::<Vec<u8>>() == TypeId::of::<Vec<String>>()
);
}Dispatch keyed on TypeId
The behavior divides between describe, which classifies one value, and main, which builds the registry.
Dispatch happens inside for value in &payloads, once per boxed value.
What to watch for
- std::any and std::collections are the entire dependency surface, both part of the standard distribution.
Applying it
The entry-point signature is fn describe(value: &dyn Any) -> &'static str
Every stage labels its line (dispatch ->, vec<u8> == vec<string>:), so the registry decisions stay traceable.
Running the file executes main, which drives describe in order.
Lines that build the registry
let payloads: Vec<Box<dyn Any>> = vec![Box::new(1u32), Box::new(String::from("text"))];
fn describe(value: &dyn Any) -> &'static str {
// type_id 给出运行期类型标识:同类型恒等,跨类型不等
if value.type_id() == TypeId::of::<u32>() {
"unsigned 32-bit"
} else if value.type_id() == TypeId::of::<String>() {
"owned string"
} else {
"unrecognized"
}
}
let name = handlers.get(&value.type_id()).copied().unwrap_or("missing");
Interactive Tools for This Topic
FAQ
- What does TypeId Runtime Type Registry print when run?
- Running the file directly is enough — expect labeled output lines such as `dispatch ->`, `vec<u8> == vec<string>:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.