Reputation: 2478
I've got two identical structs with the same name, fields (and field types), that live in different modules. These are constructed by a derive macro and would like to easily convert from one to the other.
e.g.
mod a {
struct A {
field1: String,
field2: String,
}
}
mod b {
struct A {
field1: String,
field2: String,
}
}
I'd like to be able to do let a: a::A = a::A::from(b::A)
or similar.
impl From<b::A> for a::A
requires writing all the fields from both structs in the from()
method. Is there any way to achieve this without all the associated boilerplate?
Upvotes: 6
Views: 8819
Reputation: 2478
It seems that until something like this is implemented the only way to achieve this conversion is serialising:
impl From<b::A> for a::A {
fn from(a: b::A) -> Self {
let serialised = serde_json::to_value(&a).unwrap();
serde_json::from_value(&serialised).unwrap()
}
}
Upvotes: 7