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.

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 },
}

Leave a Reply