Skip to content
เข้าสู่ระบบ

Any Trait

Runtime type introspection

use std::any::Any;
fn main() {
// Any allows runtime type checking
let values: Vec<Box<dyn Any>> = vec![
Box::new(42i32),
Box::new("hello".to_string()),
Box::new(3.14f64),
Box::new(true),
];
println!("=== Type Checking at Runtime ===");
for (i, value) in values.iter().enumerate() {
print!("Value {}: ", i);
// is<T>() checks type
if value.is::<i32>() {
println!("is i32");
} else if value.is::<String>() {
println!("is String");
} else if value.is::<f64>() {
println!("is f64");
} else if value.is::<bool>() {
println!("is bool");
}
}
// type_id() returns TypeId
let value: Box<dyn Any> = Box::new(42);
println!("\nTypeId: {:?}", value.type_id());
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด