Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I relate two generic struct fields in rust?

I have some JSON being parsed. It is structured like:

{
  elements: [{
    t: "USER",
    value: { username: "foo", age: 18 },
  },
  {
    t: "KEYBOARD",
    value: { switches: "BLUE", price: 150 }
  }]
}

I want to have some rust struct that lets me express the type of value with respect to t.

The amount of values for T is known and fixed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In short: Is there a way to have a rust struct such that:

struct Element<T> {
  t: T,
  value: SomeNewTypeDependentOn<T>
}

In TypeScript this is possible with T extends "USER" ? UserObj : T extends "KEYBOARD" ? KeyboardObj ..., but is this possible in Rust?

>Solution :

Use serde’s adjacently-tagged enums:

#[derive(serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[serde(tag = "t", content = "value")]
pub enum Elements {
    User { username: String, age: u32 },
    Keyboard { switches: String, price: u32 },
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading