是否可以定义一个与关键字同名的字段?

Dol*_*hin 8 rust serde

我正在使用 Rust 编写 REST API,我的 Flutter 客户端定义如下实体:

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

  WordDefinition({
    this.type,
    this.name,
    this.values,
  });
}
Run Code Online (Sandbox Code Playgroud)

客户端用作type实体字段名称。在 Dart 中它工作正常,但在服务器端 Rust 我无法像这样定义字段名称:

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub struct WordDefinition {
    pub type: String,
    pub text: String,
    pub translations: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
pub struct WordDefinition {
    pub type: String,
    pub text: String,
    pub translations: Vec<String>,
}
Run Code Online (Sandbox Code Playgroud)

我应该怎么做才能避免 Rust 关键字冲突?是否可以type在 Rust 中使用这样的方式定义实体名称?

cam*_*024 17

您可以通过在关键字前添加“原始标识符”来使用,r#如下所示:

struct Foo {
  r#type: String
}
Run Code Online (Sandbox Code Playgroud)

您还可以在 Rust 代码中为其指定一个名称,并用于#[serde(rename)]序列化为不同的名称。例如,这在序列化期间会kind变成type

struct Foo {
  #[serde(rename = "type")]
  kind: String
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我更喜欢第二种方式,因为我觉得r#type打字有点烦人和丑陋,但这只是偏好,没有“正确”的方式

  • @RogerLipscombe我用“kind”替换,因为它甚至在std https://doc.rust-lang.org/std/?search=kind 中也被大量使用,kind 是 https://www.wordreference.com 类型的同义词/enfr/种类。我从来没有看到过“type_”,而且我讨厌随机下划线,比如“___python___”。`clazz` 看起来很奇怪,而且 Rust 中没有类。如果你确实想使用“type”,可以使用“r#type” (3认同)
  • 将字段重命名为完全不同的名称可能会令人惊讶。例如,Java 使用 clazz(“类”),这是惯用的,但看起来很奇怪。就我个人而言,我会用下划线作为后缀(所以“type_”),但我不知道这是否是惯用的 Rust。 (2认同)