我正在使用 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打字有点烦人和丑陋,但这只是偏好,没有“正确”的方式
| 归档时间: |
|
| 查看次数: |
3527 次 |
| 最近记录: |