TypeSwitch for Rust
A powerful, Go-inspired macro to perform clean, declarative runtime type switching on dyn Any trait objects.
💡 The Inspiration
In Go, the type switch is a staple of the language:
switch v := i.(type)
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.
🚀 Features
- Clean Syntax: No more
if let Some(x) = var.downcast_ref::<Type>()boilerplate. - Go-Style Binding: Automatically bind the downcasted value to a variable for all branches using the
askeyword. - Mutability Control: Easily switch between immutable (
&T) and mutable (&mut T) access. - Owned Consumption: Move values directly out of a
Box<dyn Any>. - Or-Patterns: Match multiple types in a single branch (e.g.,
i32 | i64 => ...).
🛠 Usage
1. Automatic Binding (The "Go" Way)
By using v as subject, the identifier v is automatically bound to the concrete type in every branch.
use typeswitch;
use Any;
let x: = Boxnew;
typeswitch!;
2. Mutable Switching
Prefix the subject with mut to get mutable references in your branches.
let mut x: = Boxnew;
typeswitch!;
3. Owned Consumption
Need the actual value? Use the box keyword. This consumes the Box if the type matches.
let x: = Boxnew;
typeswitch!
4. Custom Bindings and Or-Patterns
You can define specific variable names for each arm and match multiple types.
typeswitch!
📦 Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
⚖️ License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.