Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created December 18, 2024 00:39
Show Gist options
  • Save matthewjberger/b5b5d8efdf3b251c5c74e4e655bd2304 to your computer and use it in GitHub Desktop.
Save matthewjberger/b5b5d8efdf3b251c5c74e4e655bd2304 to your computer and use it in GitHub Desktop.
Rust downcasting
use std::any::Any;
fn main() {
// Create boxes containing different types, boxed as Any
let integer_box: Box<dyn Any> = Box::new(42);
let string_box: Box<dyn Any> = Box::new(String::from("Hello"));
let float_box: Box<dyn Any> = Box::new(3.14f64);
// Demonstrate successful downcasting
println!("Downcasting examples:");
// Method 1: Using is() and downcast_ref()
if integer_box.is::<i32>() {
if let Some(value) = integer_box.downcast_ref::<i32>() {
println!("Integer (ref): {}", value);
}
}
// Method 2: Using downcast() which returns Result
match string_box.downcast::<String>() {
Ok(string_value) => println!("String (owned): {}", string_value),
Err(box_any) => println!("Downcast failed: {:?}", box_any.type_id()),
}
// Demonstrate failed downcast
println!("\nFailed downcast example:");
match float_box.downcast::<i32>() {
Ok(value) => println!("This won't print: {}", value),
Err(_) => println!("Failed to downcast f64 to i32 (as expected)"),
}
// Example with a function that returns Box<dyn Any>
let mystery_box = create_mystery_value(true);
let mystery_box2 = create_mystery_value(false);
println!("\nDowncasting mystery values:");
match mystery_box.downcast::<i32>() {
Ok(value) => println!("Mystery value was an integer: {}", value),
Err(b) => println!("Mystery value was not an integer: {:?}", b.type_id()),
}
match mystery_box2.downcast::<String>() {
Ok(value) => println!("Mystery value was a string: {}", value),
Err(b) => println!("Mystery value was not a string: {:?}", b.type_id()),
}
}
fn create_mystery_value(want_integer: bool) -> Box<dyn Any> {
if want_integer {
Box::new(42)
} else {
Box::new(String::from("Mystery solved!"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment