Crates.io | structural-convert |
lib.rs | structural-convert |
version | 0.13.0 |
source | src |
created_at | 2024-02-14 20:59:35.361702 |
updated_at | 2024-03-11 06:57:18.244419 |
description | Derive conversion traits (From, Into, TryFrom, TryInto) when fields are structurally similar in enums or structs |
homepage | |
repository | https://github.com/voidpumpkin/structural-convert/ |
max_upload_size | |
id | 1140225 |
size | 95,241 |
Derive conversion traits when items are structurally similar.
Inspired by serde and struct-convert crates.
.into()
/.try_into()
as
attributeOption
Result
std::collections
like Vec, HashMap, etc...Type
to Option<Type>
Check the tests folder for more examples, but here is some samples:
#[derive(Debug, PartialEq)]
struct Rhs {
z: i8,
x: u32,
}
#[derive(Debug, PartialEq, StructuralConvert)]
#[convert(from(Rhs))]
struct Lhs {
z: i32,
x: u32,
}
assert_eq!(Lhs { z: 1, x: 2 }, Rhs { z: 1, x: 2 }.into());
assert_eq!(Lhs { z: 1, x: 2 }, Rhs { z: 1, x: 2 }.into());
Generated code:
impl From<Rhs> for Lhs {
fn from(value: Rhs) -> Self {
match value {
Rhs { z, x } => Lhs {
z: z.into(),
x: x.into(),
},
}
}
}
#[derive(Debug, PartialEq)]
enum Rhs {
A { z: i8, x: u32 },
}
#[derive(Debug, PartialEq, StructuralConvert)]
#[convert(from(Rhs))]
enum Lhs {
A { z: i32, x: u32 },
}
assert_eq!(Lhs::A { z: 1, x: 2 }, Rhs::A { z: 1, x: 2 }.into());
Generated code:
impl From<Rhs> for Lhs {
fn from(value: Rhs) -> Self {
match value {
Rhs::A { z, x } => Lhs::A {
z: z.into(),
x: x.into(),
},
}
}
}