rust - YAML 枚举对象表示
问题描述
我有这个用例,我将在 Rust 中解释。我如何在 YAML 中表示等价物
enum MainEnum {
Opt1(T1),
Opt2(T2)
}
struct T1 {
x: u32,
}
struct T2 {
y: bool
}
我如何在 YAML 中表示这个?我希望 YaML 具有 x 字段或 y 字段,具体取决于在 YAML 中选择的 Enum 值。
该程序不运行。有任何想法吗?
use serde_yaml;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct T1 {
x: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct T2 {
y: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
enum MainEnum {
Opt1(T1),
Opt2(T2),
}
fn main() {
let config = r#"
---
- Opt1
x: "true"
"#;
let me: MainEnum = serde_yaml::from_str(&config).unwrap();
println!("{:?}", me);
}
运行时错误:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Scan(ScanError { mark: Marker { index: 17, line: 4, col: 5 }, info: "mapping values are not allowed in this context" })', src/main.rs:27:25
解决方案
第一个问题似乎是您使用的 YAML 语法。对于 YAML 中的地图,您需要使用:
so终止父级
let config = r#"
---
- Opt1:
x: true
"#;
实际上是正确的 YAML。但是,由于您向 serde_yaml 询问 MainEnum 的一个实例,而不是 MainEnum 的列表(例如 vec),因此它不需要 YAML 序列而是单个条目:
fn main() {
let config = r#"
---
Opt1:
x: true
"#;
let me: MainEnum = serde_yaml::from_str(&config).unwrap();
println!("{:?}", me);
}
推荐阅读
- php - 为什么整数上的 in_array 严格模式比非严格模式慢?
- tensorflow - 模块“tensorrt”没有属性“记录器”
- java - Spring MVC 转换 Spring Rest Api
- javascript - 从 ember lodash 中查找嵌套属性并选择值
- javascript - 错误无法读取未定义的属性“transpile”
- python - Coral Edge TPU 编译器无法转换 tflite 模型:模型未量化
- sharepoint - 如何根据其 GUID 获取 SharePoint 文件夹详细信息
- google-sheets - 如何拆分单元格值并将结果与另一个单元格的结果进行比较?
- python - 如何调用通过 tkinter filedialog 导入的文件?
- reactjs - 使用相同的组件多次使用相同的 reducer 和每个被调用组件的状态变量实例