Changing the case of names

serde_derive maps names of fields in the code to fields of data. For example, the title field of a struct will expect the title field of a data object. If the protocol uses other names for fields, you have to take this into account to avoid warnings. For example, a struct in a protocol might contain the stdDev field, but if you use the name of this field in Rust, you get the following warning:

warning: variable `stdDev` should have a snake case name such as `std_dev`

You can fix this adding the #![allow(non_snake_case)] attribute, but this makes the code unsightly. A better solution is to use the #[serde(rename="stdDev")] attribute and use the other naming convention for serialization and deserialization only.

There are two variants of renaming attributes:

  • Changing the naming convention for all variants
  • Changing the name of a field

To change all variants of an enumeration, add the #[serde(rename_all="...")] attribute with one of the following values: "lowercase", "PascalCase", "camelCase", "snake_case", "SCREAMING_SNAKE_CASE", or "kebab-case". To be more representative, naming values are written according to the rules of their own convention.

To change the name of a field, use the #[serde(rename="...")] attribute with the name of the field used in the serialization process. You can see an example of the usage of this attribute in Chapter 17, Bounded Microservices with AWS Lambda.

Another reason to use renaming is when the names of fields are keywords in Rust. For example, a struct can't contain a field with the popular name type, because it's a keyword. You can rename it to typ in the struct and add #[serde(rename="type")] to it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.47.208