rust - 是否可以使用 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 中无法按预期工作。
解决方案
您可以通过为以下关键字添加前缀来使用“原始标识符”:r#type
。
你可能还想在你的 Rust 代码中给它一个不同的名字,并用#[serde(rename)]
它来序列化它的名字“type”,比如:
struct Foo {
#[serde(rename = "type")]
kind: String
}
就个人而言,我更喜欢第二种方式,因为我觉得r#type
打字有点烦人而且很难看,但这只是偏好,没有“正确”的方式
推荐阅读
- vim - 匹配具有不同前面零宽度模式的相同字符串
- drupal - 在 Drupal 8 中以编程方式保存 geofield
- android - 在 Samsung Galaxt S9 (Oreo) 上显示安全异常
- xml - 在命名空间定义中使用变量
- botframework - Botframework WebChat:无法在其他聊天/浏览器上开始新的和干净的对话
- php - Ajax 获取表单 PHP MySQL 的提交按钮的动态 id
- nfc - 如何开始与 ACR122U-A9 NFC 读写器交互?
- java - java将结果集转换为列表
- cordova - 基于 Cordova 的应用程序启动画面延迟不适用于 Windows 10 版本
- java - 基于 java 的项目环境设置的 sonar.java.binaries 属性中的错误