- serde
- serde_yml
- from_reader
- as_i64
- as_str
- struct
- TODO
Read YAML file
- TODO: if the number of dashes at the top is not correct (e.g. 4, the parser will panic, how to handle this properly?)
Hello World! 3 data = Point { x: 1, y: 2, text: "Hello World!" } 3 Hello World!
examples/yaml/read-yaml-file/data.yaml
--- x: 1 y: 2 text: Hello World!
examples/yaml/read-yaml-file/Cargo.toml
[package] name = "read-yaml-file" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] serde = { version = "1.0", features = ["derive"] } serde_yml = "0.0.12"
examples/yaml/read-yaml-file/src/main.rs
use std::fs::File; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, text: String, } fn main() { read_any_yaml(); read_struct_yaml(); } fn read_any_yaml() { let filename = "data.yaml"; match File::open(filename) { Ok(file) => { let data: serde_yml::Value = serde_yml::from_reader(file).expect("YAML parsing error"); dbg!(&data); let text = match data.get("text") { Some(val) => val.as_str().unwrap(), None => panic!("Field text does not exist"), }; println!("{}", text); let x = match data.get("x") { Some(val) => val.as_i64().unwrap(), None => panic!("Field x does not exist"), }; let y = match data.get("y") { Some(val) => val.as_i64().unwrap(), None => panic!("Field y does not exist"), }; println!("{}", x + y); } Err(error) => { println!("Error opening file {}: {}", filename, error); } } } fn read_struct_yaml() { let filename = "data.yaml"; match File::open(filename) { Ok(file) => { let data: Point = serde_yml::from_reader(file).unwrap(); println!("data = {:?}", data); println!("{}", data.x + data.y); println!("{}", data.text); assert_eq!(data.x, 1); assert_eq!(data.y, 2); assert_eq!(data.text, "Hello World!"); } Err(error) => { println!("Error opening file {}: {}", filename, error); } } }
Hello World! 3 data = Point { x: 1, y: 2, text: "Hello World!" } 3 Hello World!