2

I want to avoid code repetition as much as possible.

use serde::{Deserialize, Serialize};
use serde_json::Result;

#[derive(Serialize, Deserialize, Debug)]
enum AttibuteType {
    #[serde(rename = "ID")]
    Id,
    #[serde(rename = "STRING")]
    String,
    #[serde(rename = "BOOL")]
    Bool,
    #[serde(rename = "NUMERIC")]
    Numeric,
    #[serde(rename = "ARRAY")]
    Array
}

#[derive(Serialize, Deserialize, Debug)]
struct Attribute {
    name: String,
    #[serde(rename(deserialize = "dataType"))]
    attribute_type: AttibuteType,
    #[serde(rename(deserialize = "of"))]
    array_attribute_type: Option<String>
}

fn typed_example() -> Result<()> {

    let data = r#"
        {
            "name": "John Doe",
            "dataType": "ID",
            "of" : "STRING"
        }"#;

    let p: Attribute = serde_json::from_str(data)?;

    println!("{:?}", p);

    Ok(())
}

fn main() {
    typed_example().unwrap();
}

playground

I cannot change, at this stage of the project, the data that are being sent (names, values etc.), so I decided to rename and manipulate them in Rust. I am not sure if I am going to the correct direction by using all those rename tags for enums. Currently the "client" sends some strings, all capital. I want to be sure that my Rust server accepts only those values (ID, STRING, BOOL, NUMERIC, ARRAY). Is the definition of AttributeType above adequate to satisfy that need?

Is there any other more elegant way instead of using rename to each enum value to ask from serde to make all values PascalCase?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
malefstro
  • 149
  • 9
  • Your code works, so it appears that you've **already answered your own question**. If you are seeking review of working code, [Code Review](https://codereview.meta.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users) may be more appropriate. – Shepmaster May 05 '20 at 20:30
  • Removed the question about crash, there is no error handling in place yet. I updated my question. – malefstro May 05 '20 at 20:33
  • *to make all values PascalCase* — your values are not PascalCase — they are all caps. – Shepmaster May 05 '20 at 20:38
  • [The duplicate applied to your situation](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d71dd584e44e06ec283fa0e41de5e25a) – Shepmaster May 05 '20 at 20:41
  • 1
    a duplicate indeed. makes sense when you are using a platform for the first time. Thanks – malefstro May 05 '20 at 20:44

0 Answers0