【问题标题】:Serde how to access a field of a struct cast to `impl Serialize`?Serde 如何访问 struct cast 到`impl Serialize`的字段?
【发布时间】:2022-11-02 14:23:03
【问题描述】:

我试图弄清楚如何访问结构转换的字段以“实现序列化”?

考虑以下代码:

mod Testing {
    #[derive(Serialize, Clone)]
    pub struct One {
        pub valueOne: String,
    }

    #[derive(Serialize, Clone)]
    pub struct Two {
        pub valueOne: String,
        pub valueTwo: String,
    }
}

fn go() -> Result<()> {
    let s = Testing::One {
        valueOne: "Please work",
    };
    self.how(s);
    Ok(())
}

fn how(
    s: impl Serialize,
) -> Result<()> {
    // How to access "valueOne" of "s"?
    Ok(())
}

【问题讨论】:

  • 你不能。但这看起来像一个 XY 问题。
  • 你实际上想要完成什么?

标签: rust traits serde


【解决方案1】:

您无法访问how() 中的字段valueOne,即使OneTwo 都有该字段。在how() 中对s 的所有了解是它实现了Serialize,这不足以保证它甚至具有valueOne 字段。 s 可以是 OneTwo 或任何其他也恰好实现 Serialize 并且不包括字段 valueOne 的随机类型。

正确的做法是引入另一个为valueOne 提供吸气剂的特征。然后,您可以依靠 trait 为您提供该价值。

trait ValueOne {
    fn value_one(&self) -> &str;
}

#[derive(Serialize)]
pub struct One {
    pub value_one: String,
}

impl ValueOne for One {
    fn value_one(&self) -> &str {
        &self.value_one
    }
}

#[derive(Serialize)]
pub struct Two {
    pub value_one: String,
    pub value_two: String,
}

impl ValueOne for Two {
    fn value_one(&self) -> &str {
        &self.value_one
    }
}

fn go() {
    let s = One {
        value_one: "Please work".to_owned(),
    };
    how(s);
}

fn how(s: impl Serialize + ValueOne) {
    dbg!(s.value_one());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-06
    • 2020-07-19
    • 2022-01-04
    • 2020-09-07
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多