derive-into
A Rust derive macro for easily creating conversions between structs and enums.
Features
- Automate conversions between similar data structures
- Support for struct-to-struct, tuple struct, and enum conversions
- Field renaming capabilities
- Automatic handling of wrapped types with
From/Intoimplementations - Special handling for
OptionandVectypes - Support for both infallible (
From) and fallible (TryFrom) conversions - Fine-grained control with field-level attributes
Installation
Add to your Cargo.toml:
[]
= "0.1.0"
Quick Start
use Convert;
// Source struct with conversion attributes
// Generate Into<Destination> implementation
// Destination struct
// Usage
let source = Source ;
let destination: Destination = source.into;
Conversion Types
The macro supports the following conversion types:
| Attribute | Description |
|---|---|
#[convert(into = "Type")] |
Implements Into<Type> for the struct/enum |
#[convert(try_from = "Type")] |
Implements TryFrom<Type> for the struct/enum |
#[convert(from = "Type")] |
Implements From<Type> for the struct/enum |
Struct-Level Attributes
| Attribute | Description |
|---|---|
#[convert(into = "Type")] |
Generate an Into<Type> implementation |
#[convert(try_from = "Type")] |
Generate a TryFrom<Type> implementation |
#[convert(from = "Type")] |
Generate a From<Type> implementation |
#[convert(default)] |
Use Default::default() for fields not explicitly mapped |
Field-Level Attributes
| Attribute | Description |
|---|---|
#[convert(rename = "new_name")] |
Map this field to a differently named field in the target type |
#[convert(unwrap)] |
Automatically unwrap an Option value (fails in try_from if None) |
#[convert(skip)] |
Skip this field during conversion (target must provide a default) |
Enum Conversion
The macro supports enum-to-enum conversion with similar attribute control:
Type Conversions
The macro intelligently handles various type scenarios:
- Direct Mapping: Fields with identical types are directly copied
- Automatic Conversion: Fields with types that implement
From/Intoare automatically converted - Container Types: Special handling for
Option<T>andVec<T>with inner type conversion - Tuple Structs: Support for conversions between tuple structs
Examples
Basic Struct Conversion
use Convert;
// Usage
let source = Source ;
let target: Target = source.into;
Handling Option and Vec Types
The macro automatically handles conversion of inner types for Option and Vec:
use Convert;
;
Using Unwrap for Options
use Convert;
// This will succeed
let source = Source ;
let target: = try_from;
assert!;
// This will fail because value is None
let source = Source ;
let target: = try_from;
assert!;
Using Default Values
use Convert;
Advanced Usage
Custom Type Conversion
The macro leverages existing From/Into implementations for field types:
use Convert;
;
License
This project is licensed under the MIT License - see the LICENSE file for details.