Read Yaml File in Rust

Dependencies

add yaml-rust = "0.4" in your Cargo.toml or run cargo add yaml-rust

Code

1
2
3
4
# file.yaml
clean:
- ~/
- ~/.config
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// main.rs
use std::fs::File;
use std::io::prelude::*;
use yaml_rust::YamlLoader;

fn main() {
let file = "file.yaml";
let mut file = File::open(file).expect("Unable to open file");
let mut contents = String::new();

file.read_to_string(&mut contents)
.expect("Unable to read file");

let docs = YamlLoader::load_from_str(&contents).unwrap();
let yaml = &docs[0];
// println!("{:#?}", yaml);
let clean = yaml["clean"][0].as_str().unwrap();
println!("{clean}");
}

result for cargo run:

1
~/

References


Read Yaml File in Rust
https://xxiaoa.github.io/posts/d42e5e77/
Author
XXiaoA
Posted on
August 24, 2022
Licensed under