dtype_variant
A Rust derive macro for creating type-safe enum variants with shared type tokens across multiple enums. This enables synchronized variant types and powerful downcasting capabilities between related enums.
Features
- 🔄 Share and synchronize variant types across multiple enums
- ✨ Type-safe downcasting of enum variants using token types
- 🔒 Compile-time validation of variant types
- 📦 Optional container type support (e.g., Vec, Box)
- 🔍 Constraint trait implementation for variant types
- 🎯 Flexible pattern matching through generated macros
- 🛠️ Convenient From implementations for variant types
Why?
Let's say you're building a data processing pipeline where you need to handle different numeric types. Without dtype_variant, you might start with something like this:
// Define types that your system can handle
// Store actual data
// Processing functions
This approach has several problems:
- Type Safety: There's no compile-time guarantee that
NumericTypeandNumericDatavariants stay in sync - Boilerplate: You need to write conversion methods for each type
- Extensibility: Adding a new numeric type requires changes in multiple places
- Error-prone: Easy to forget updating one enum when modifying the other
With dtype_variant, this becomes:
use DType;
Now you get:
- Type Safety: Downcasting is handled through token types at compile time
- Zero Boilerplate: Generic downcasting methods are automatically implemented
- Easy Extension: Just add a new variant and its token type
- Pattern Matching: Generated macros for ergonomic handling
// Or use the generated pattern matching macro
match_numeric!;
The crate especially shines when you have multiple related enums that need to stay in sync:
All these enums share the same token types, ensuring they stay in sync and can safely interact with each other through the type system.
Installation
Add this to your Cargo.toml:
[]
= "0.0.1"
Usage
use DType;
// First, define your token types (usually generated)
Features
Type-safe Downcasting
Access variant data with compile-time type checking:
let num = Float;
// Safe downcasting methods
let float_ref: = num.;
let float_mut: = num.;
let owned_float: = num.;
Container Types
Optionally wrap variant data in container types:
Trait Constraints
Enforce trait bounds on variant types:
Pattern Matching
Generate ergonomic pattern matching macros:
match_data!;
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Acknowledgements
This project was inspired by dtype_dispatch, which provides similar enum variant type dispatch functionality.