如何在 Rust 中读取 YAML 文件? [英] How do you read a YAML file in Rust?
本文介绍了如何在 Rust 中读取 YAML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我戳了 serde-yaml 和 yaml-rust 有点板条箱,但我还没有看到任何例子.
I've poked the serde-yaml and yaml-rust crates a bit, but I haven't seen any examples.
推荐答案
serde-yaml 的文档有以下4个功能:
from_reader
— 反序列化来自 YAML IO 流的T
类型的实例.from_slice
— 反序列化来自 YAML 文本字节的T
类型的实例.from_str
— 反序列化来自 YAML 文本字符串的T
类型的实例.from_value
— 解释serde_yaml::Value
作为T
类型的实例.
from_reader
— Deserialize an instance of typeT
from an IO stream of YAML.from_slice
— Deserialize an instance of typeT
from bytes of YAML text.from_str
— Deserialize an instance of typeT
from a string of YAML text.from_value
— Interpret aserde_yaml::Value
as an instance of typeT
.
以from_reader
为例:
use serde_yaml; // 0.8.7
fn main() -> Result<(), Box<std::error::Error>> {
let f = std::fs::File::open("something.yaml")?;
let d: String = serde_yaml::from_reader(f)?;
println!("Read YAML string: {}", d);
Ok(())
}
something.yaml:
"I am YAML"
您可以反序列化为更宽松的类型 Value
如果您不知道您的格式(本示例中为 String
),但请务必阅读 Serde 指南 了解如何进行类型定向序列化和反序列化的完整详细信息.
You can deserialize into the looser-typed Value
if you don't know your format (String
in this example), but be sure to read the Serde guide for full details of how to do type-directed serialization and deserialization instead.
另见:
一般来说,使用 any Serde 格式与其他所有格式几乎相同.
In general, using any Serde format is pretty much the same as all the rest.
这篇关于如何在 Rust 中读取 YAML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文