I have a couple of structs (StructX and StructY), and another struct that has all the common reference properties of the previous ones (StructCommon).
I also have a function for each of StructX and StructY that returns a StructCommon, but my issue is that I had to write two functions for it.
pub struct StructX<'a> {
a: &'a str,
b: &'a str,
x: &'a str,
}
pub struct StructY<'a> {
a: &'a str,
b: &'a str,
y: &'a str,
}
pub struct StructCommon<'a> {
a: &'a str,
b: &'a str,
}
impl<'a> StructCommon<'a> {
pub fn from_x<T>(serialized: &StructX) -> StructCommon<'a>
{
StructCommon {
a: serialized.a,
b: serialized.b,
}
}
pub fn from_y<T>(serialized: &StructY) -> StructCommon<'a>
{
StructCommon {
a: serialized.a,
b: serialized.b,
}
}
// Pseudo-Rust proposed solution example:
// pub fn from_either<T>(serialized: &StructX | &StructY) -> StructCommon<'a>
// {
// StructCommon {
// a: serialized.a,
// b: serialized.b,
// }
// }
}
How can I - if possible - deduplicate the from_x() and from_y() methods so I would only have to write the logic for extracting the common properties only once**?**
I have written an imaginary pseudo-code solution example method commented out called from_either().