Search code examples
rustserde

Is it possible to define a field with the same name as a keyword?


I am using Rust to write a REST API and my Flutter client defines the entity like this:

class WordDefinition {
  String type;
  String name;
  List<String> values;

  WordDefinition({
    this.type,
    this.name,
    this.values,
  });
}

The client uses type as a entity field name. In Dart it works fine, but in the server side Rust I could not define the field name like this:

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub struct WordDefinition {
    pub type: String,
    pub text: String,
    pub translations: Vec<String>,
}
error: expected identifier, found keyword `type`
 --> src/lib.rs:5:9
  |
4 | pub struct WordDefinition {
  |            -------------- while parsing this struct
5 |     pub type: String,
  |         ^^^^ expected identifier, found keyword

What should I do to avoid the Rust keyword conflict? Is it possible to define a entity name using type like this in Rust?


Solution

  • You can use "raw identifiers" by prefixing a keyword withr# like this:

    struct Foo {
      r#type: String
    }
    

    You can also give it one name in your Rust code and use #[serde(rename)] to serialize to a different name. For example, this changes kind into type during serialization:

    struct Foo {
      #[serde(rename = "type")]
      kind: String
    }
    

    Personally, I prefer the second way, because I find r#type a bit annoying to type and ugly, but that's just preference, there's not a "right" way