| Crates.io | typeswitch |
| lib.rs | typeswitch |
| version | 0.1.0 |
| created_at | 2026-01-07 02:05:29.146258+00 |
| updated_at | 2026-01-07 02:05:29.146258+00 |
| description | A powerful, Go-inspired macro for clean and declarative runtime type switching on dyn Any trait objects. |
| homepage | |
| repository | https://github.com/veecore/typeswitch |
| max_upload_size | |
| id | 2027281 |
| size | 17,269 |
A powerful, Go-inspired macro to perform clean, declarative runtime type switching on dyn Any trait objects.
In Go, the type switch is a staple of the language:
switch v := i.(type) {
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown")
}
In standard Rust, downcasting dyn Any usually requires a tedious chain of if-let blocks. typeswitch brings that ergonomic Go-style syntax to Rust while respecting Rust's strict rules on ownership, mutability, and borrowing.
if let Some(x) = var.downcast_ref::<Type>() boilerplate.as keyword.&T) and mutable (&mut T) access.Box<dyn Any>.i32 | i64 => ...).By using v as subject, the identifier v is automatically bound to the concrete type in every branch.
use typeswitch::typeswitch;
use std::any::Any;
let x: Box<dyn Any> = Box::new(42i32);
typeswitch!(v as x {
i32 => println!("It's an i32: {}", v + 1),
String => println!("It's a string: {}", v.as_str()),
_ => println!("Unknown type"),
});
Prefix the subject with mut to get mutable references in your branches.
let mut x: Box<dyn Any> = Box::new(100i32);
typeswitch!(mut v as x {
i32 => { *v += 1; },
_ => {},
});
Need the actual value? Use the box keyword. This consumes the Box if the type matches.
let x: Box<dyn Any> = Box::new(String::from("Ownership!"));
typeswitch! { x {
box s: String => println!("Consumed string: {}", s),
_ => println!("Not a string, box is still alive here."),
}}
You can define specific variable names for each arm and match multiple types.
typeswitch! { x {
i32 | i64 => println!("Some integer"),
s: String => println!("String: {}", s),
_ => println!("Fallback"),
}}
Add this to your Cargo.toml:
[dependencies]
typeswitch = "0.1.0"
Licensed under either of Apache License, Version 2.0 or MIT license at your option.