首页 > 解决方案 > 是否可以使用 rust 中的关键字定义字段

问题描述

我正在使用rust编写一个rest api,现在fluter客户端定义这样的实体:

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

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

客户端使用type作为实体字段名称,在飞镖它工作正常。但是在服务器端rust我不能这样定义字段名,在定义实体时应该怎么做才能避免rust关键字限制?是否可以type在 rust 中使用这样的方式定义实体名称:

use rocket::serde::Deserialize;
use rocket::serde::Serialize;

#[derive(Deserialize, Serialize)]
#[allow(non_snake_case)]
pub struct WordDefinition {
    pub type: String,
    pub text: String,
    pub translations: Vec<String>,
}

impl Default for WordDefinition {
    fn default() -> Self {
        WordDefinition {
            type: "".to_string(),
            text: "".to_string(),
            translations: vec![]
        }
    }
}

我是这样定义的,但显然它在 rust 中无法按预期工作。

标签: rust

解决方案


您可以通过为以下关键字添加前缀来使用“原始标识符”:r#type

你可能还想在你的 Rust 代码中给它一个不同的名字,并用#[serde(rename)]它来序列化它的名字“type”,比如:

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

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


推荐阅读