Home > OS >  Get an object from a struct with an array inside
Get an object from a struct with an array inside

Time:05-16

I have this json from an external:

  "description": {
    "type": "doc",
    "version": 1,
    "content": [
      {
        "type": "paragraph",
        "content": "data",
      }
    ]
  },

And I want to create and object with a struct

#[derive(Debug, Serialize, Deserialize)]
struct Content {
  type: String,
  content: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Description {
  type: String,
  version: i32,
  content: [Content;1],
}

And now the object

let data = Description {
    type: "doc".into(),
    version: 1,
    content: Content [{
       type: "paragraph".into(),
       content: "data".into(),
   }]
}

Two problems:

  1. The code gives me an error within the struct, with the word "type", I think it is because it's reserved in Rust.
type: String,
  1. The other error is when I create the object in the content array.
Content [{
    type: "paragraph".into(),
    content: "data".into(),
}]

CodePudding user response:

For your first point: yes type is reserved in Rust. You can fix this by renaming the field through serde:

#[derive(Debug, Serialize, Deserialize)]
struct Content {
  #[serde(rename = "type")]
  content_type: String,
  content: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Description {
  #[serde(rename = "type")]
  descr_type: String,
  version: i32,
  content: [Content;1],
}

Alternatively you could escape it by replacing it with r#type, but renaming through serde is generally preferred over that.

For your second point, that's not how you make an array in Rust. You simply place the value(s) in the []s, like so:

let data = Description {
    type: "doc".into(),
    version: 1,
    content: [
       Content {
          type: "paragraph".into(),
          content: "data".into(),
       }
   ]
}

You may also want to consider replacing that with a Vec depending on how strong your guarantees are regarding the incoming data.

CodePudding user response:

Regarding the two problems:

  1. Yes, type is a reserved keyword in Rust. For the Content struct, maybe use content_type, and for the Description struct, use description_type.
  2. type is also the error here. You also didn't write the content field correctly. It should be:
let data = Description {
    desc_type: "doc".into(),
    version: 1,
    content: [
        Content {
            content_type: "paragraph".into(),
            content: "data".into(),
        }
    ],
};
  • Related