Rust Dataclass Macro
A Rust procedural macro that implements Python-style dataclasses. This macro helps reduce boilerplate code by automatically implementing common traits and generating constructors for your structs.
Features
- Similar API to Python's
@dataclassdecorator - Customizable trait implementations
- Supports frozen (immutable) classes
- Memory layout optimization options
- Automatic constructor generation
- Optional serde support
Installation
Add this to your Cargo.toml:
[]
= "0.1.0" # Replace with actual version
Usage
Basic usage:
use dataclass;
// Use all default options
// With custom options
Options
| Option | Default | Description |
|---|---|---|
init |
true |
Generate a constructor |
repr |
true |
Implement Debug trait |
eq |
true |
Implement PartialEq and Eq traits |
order |
false |
Implement Ord and PartialOrd traits |
unsafe_hash |
false |
Implement Hash trait |
frozen |
false |
Make fields immutable (pub(crate)) |
match_args |
true |
Enable pattern matching support |
kw_only |
false |
Constructor requires named arguments |
slots |
false |
Optimize memory layout |
weakref_slot |
false |
Reserved for future use |
Generated Code
For a basic struct with default options, the macro generates:
// Your code
// Generated code
Feature Flags
serde: Enable serde support for serialization/deserialization
[]
= { = "0.1.0", = ["serde"] }
Examples
Basic Point Structure
use dataclass;
let point = new;
println!; // Point { x: 10, y: 20 }
Ordered Data Structure
let v1 = new;
let v2 = new;
assert!; // Comparison works
Immutable Structure
let config = new;
// config.value = 43; // This would cause a compilation error
With Serde Support
use dataclass;
use ;
For more detailed serde integration examples, including custom serialization, working with complex types, and different formats, see SERDE.md.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Comparison with Python's Dataclass
This macro aims to provide similar functionality to Python's dataclass decorator while remaining true to Rust's patterns and safety guarantees. The main differences are:
- No default values in struct definition (use Default trait instead)
- No post-init processing (use custom impl blocks)
- No field order specification (follows struct definition order)
- Additional memory optimization options
- Rust-specific features like pub/pub(crate) visibility
Known Limitations
- Limited support for generic types (work in progress)
- No support for custom derive implementations
- Field attributes are not processed