我有許多包含Builder
結構的結構體。這些包裝提供了這個Builder
的專門行爲。在這些包裝器之間轉換應該很容易,因爲它們本質上只是具有專門方法的Builder
。我寫了一些代碼來說明 - 對於簡單的東西來說,它似乎有很多樣板。有沒有更好的辦法?有沒有更好的方法來使用From和Into來共享公共內部域的結構
struct Builder;
trait ObjectBuilder: Into<Builder> + From<Builder> {
fn from_other<T: ObjectBuilder>(x: T) -> Self {
let builder = x.into();
builder.into()
}
}
struct OtherBuilder {
inner: Builder
}
impl From<Builder> for OtherBuilder {
fn from(x: Builder) -> OtherBuilder {
OtherBuilder {
inner: x
}
}
}
impl Into<Builder> for OtherBuilder {
fn into(self) -> Builder {
self.inner
}
}
struct OtherOtherBuilder {
inner: Builder
}
impl From<Builder> for OtherOtherBuilder {
fn from(x: Builder) -> OtherOtherBuilder {
OtherOtherBuilder {
inner: x
}
}
}
impl Into<Builder> for OtherOtherBuilder {
fn into(self) -> Builder {
self.inner
}
}
impl ObjectBuilder for OtherBuilder {}
impl ObjectBuilder for OtherOtherBuilder {}
fn main() {
let x = Builder;
let y: OtherBuilder = x.into();
let z: OtherOtherBuilder = ObjectBuilder::from_other(y);
let y = OtherBuilder::from_other(z);
}
您可以使用[newtype_derive](https://danielkeep.github.io/rust-custom-derive/doc/newtype_derive/index .html)條目,但只適用於元組結構,即'struct OtherBuilder(Builder)'。 – kennytm