Nodyn
Easy polymorphism with enums
nodyn provides a Rust macro for creating wrapper enums that
encapsulate a fixed set of types with automatic implementations
for From, TryFrom, and delegated methods or traits. This is
ideal for scenarios where you need to store values of different
types in a type-safe, zero-cost way, as an alternative to trait
objects.
"This is a perfectly good solution when our interchangeable items are a fixed set of types that we know when our code is compiled."
The Rust Programming Language
Features
- Method and Trait Delegation: Delegates methods or entire traits to the underlying types.
- Automatic Variant Creation: Generates an enum with variants for specified types (e.g.,
i32,String, custom structs). - Type Conversion: Implements
From<T>for each variant type andTryFrom<Enum> for Tfor non-reference types. - Type Introspection: Provides utility methods like
count(),types(), andtype_name()to query variant information. - Custom Variant Names: Allows overriding default variant names for clarity.
- Supported Types: Handles path types, references, arrays and tuples.
Installation
Add nodyn to your Cargo.toml:
[]
= "0.1.0"
Basic example
use wrap;
wrap!
Method Delegation Example
nodyn!
let mut container: Container = "hello".to_string.into;
assert_eq!;
assert!;
Trait Implementation Example
use ;
// All wrapped types implement Display
nodyn!
let values: = vec!;
for val in values
Advanced Example
use fmt;
;
//!
;
nodyn!
let values: = vec!;
for val in &values
// null: null
// boolean: true
// number: 42
// string: hello
// array: [null, false, 33, world]
Features
All features are enabled by default.
| Feature | enables |
|---|---|
from |
automatic From trait implementation |
try_into |
automatic TryFrom trait implementation |
introspection |
generation of type introspection functions |
is_as |
generation of variant test and accessor functions |
📚 Documentation
🆚 Comparison
| Feature | nodyn | enum_dispatch | sum_type | Box<dyn Trait> |
|---|---|---|---|---|
| Runtime cost | Zero | Zero | Zero | Heap allocation |
| Trait delegation | ✅ Yes | ✅ Scoped only | ❌ No | ✅ Yes |
| Method delegation | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
| Type introspection | ✅ Built-in | ❌ No | ❌ No | ❌ No |
| Compile-time known | Required | Required | Required | Not required |
| Memory overhead | Discriminant only | Discriminant only | Discriminant only | Pointer + vtable |
- enum_dispatch: Near drop-in replacement for dynamic-dispatched method calls with up to 10x the speed.
- sum_type: A convenience macro for creating a wrapper enum which may be one of several distinct types.
License
This project is licensed under the MIT License - see the LICENSE file for details.