Type Erasure With Any Downcast

Downcast Box<dyn Any> values back to concrete types so heterogeneous registries stay type safe without enums or unsafe code.

RustData Integrity

Code

rustsnippet
37 lines
use std::any::Any;

#[derive(Debug)]
struct Request {
    id: u32,
}

fn main() {
    // Box<dyn Any>:同一容器存放任意具体类型
    let values: Vec<Box<dyn Any>> = vec![
        Box::new(42u32),
        Box::new(String::from("hello")),
        Box::new(Request { id: 7 }),
    ];

    for value in &values {
        if let Some(number) = value.downcast_ref::<u32>() {
            println!("u32: {number}");
        } else if let Some(text) = value.downcast_ref::<String>() {
            println!("String: {text}");
        } else if let Some(req) = value.downcast_ref::<Request>() {
            println!("Request: id={}", req.id);
        }
    }

    // 可变借用取回具体类型后原地修改
    let mut owned: Box<dyn Any> = Box::new(99i64);
    if let Some(number) = owned.downcast_mut::<i64>() {
        *number += 1;
    }
    match owned.downcast::<i64>() {
        Ok(boxed) => println!("owned i64: {}", *boxed),
        Err(_) => println!("unexpected type"),
    }

    println!("first is u32: {}", values[0].is::<u32>());
}

How it works

Type Erasure With Any Downcast comes down to the function main.

Repetition is confined to for value in &values — the rest of the file is straight-line. Pattern matching via match forces each shape of the value to be handled.

Putting it to use

The main signature reads fn main()

The demo output is labeled (u32:, String:, Request: id=), so every printed line maps back to its originating operation.

Core lines

let mut owned: Box<dyn Any> = Box::new(99i64);
let values: Vec<Box<dyn Any>> = vec![
    Box::new(42u32),
    Box::new(String::from("hello")),
    Box::new(Request { id: 7 }),
];
if let Some(number) = value.downcast_ref::<u32>() {
    println!("u32: {number}");
} else if let Some(text) = value.downcast_ref::<String>() {
    println!("String: {text}");
} else if let Some(req) = value.downcast_ref::<Request>() {
    println!("Request: id={}", req.id);
}

Interactive Tools for This Topic

FAQ

What does Type Erasure With Any Downcast print when run?
Invoke the file as-is — the `u32:`, `String:`, `Request: id=` prefixes identify which step printed each line.