【问题标题】:How can I convert a struct to another struct with exactly the same field names and types?如何将结构转换为具有完全相同字段名称和类型的另一个结构?
【发布时间】:2021-08-14 19:13:19
【问题描述】:

我有两个具有相同名称、字段(和字段类型)的相同结构,它们位于不同的模块中。这些是由派生宏构造的,并且希望轻松地从一个转换为另一个。

例如

mod a {
    struct A {
        field1: String,
        field2: String,
    }
}

mod b {
    struct A {
        field1: String,
        field2: String,
    }
}

我希望能够做到let a: a::A = a::A::from(b::A) 或类似的。

impl From<b::A> for a::A 需要在from() 方法中写入两个结构中的所有字段。如果没有所有相关的样板文件,有什么方法可以实现这一点?

【问题讨论】:

标签: struct rust type-conversion


【解决方案1】:

似乎在实现this 之类的东西之前,实现这种转换的唯一方法是序列化:

impl From<b::A> for a::A {
    fn from(a: b::A) -> Self {
        let serialised = serde_json::to_string(&a).unwrap();
        serde_json::from_str(&serialised).unwrap()
    }
}

Source

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 2017-08-31
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多