Crates.io | default-conversion |
lib.rs | default-conversion |
version | 0.2.0 |
source | src |
created_at | 2020-10-19 23:26:17.537183 |
updated_at | 2020-10-20 07:06:35.986954 |
description | A derive macro to automatic implement conversions between similar structs |
homepage | https://github.com/AurelienFT/default-conversion-rs |
repository | https://github.com/AurelienFT/default-conversion-rs |
max_upload_size | |
id | 303186 |
size | 10,503 |
Default conversion for structures with same fields of the same name
I discovered this way to do the same job of this crate: https://stackoverflow.com/questions/57477967/how-can-i-use-serde-to-serialize-a-struct-to-another-rust-data-structure
But apparently my way to do it with From is faster : https://github.com/serde-rs/json/issues/724
Some projects which use derive proc macros need separates structures with similar "structures" to make different things. For example :
default-conversion = "0.1.0"
struct B {
a: i32,
};
#[derive(IntoDefault)]
#[IntoStruct(B)]
struct InputB {
a: i32,
};
struct A {
a: String,
b: i32,
c: B
};
#[derive(IntoDefault)]
#[IntoStruct(A)]
struct InputA {
a: String,
b: i32,
#[IntoType(B)]
c: InputB
};
let a = InputA {
a: String::from("test"),
b: 2,
c: InputB {
a: 3
}
};
let b = A::from(a);
struct B {
a: i32,
};
#[derive(IntoDefault)]
#[IntoStruct(B)]
struct InputB {
a: i32,
};
impl From<InputB> for B {
fn from(item: InputB) -> Self {
B {
a: item.a.into()
}
}
}
struct A {
a: String,
b: i32,
c: B
};
#[derive(IntoDefault)]
#[IntoStruct(A)]
struct InputA {
a: String,
b: i32,
#[IntoType(B)]
c: InputB
};
impl From<InputA> for A {
fn from(item: InputA) -> Self {
A {
a: item.a.into(),
b: item.b.into(),
c: item.c.into()
}
}
}
let a = InputA {
a: String::from("test"),
b: 2,
c: InputB {
a: 3
}
};
let b = A::from(a);
Detailed explanations in docs (soon xd).
IntoDefault
is the main derive macro to invoke the from implementation.
IntoStruct
the attribute proc macro to define the type in which we want to implement the conversion. #[IntoStruct(TYPE_OF_STRUCT)]