Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Comments¶
- The serde_yaml crate is the best tool for parsing YAML in Rust.
In [2]:
:sccache 1
:dep serde = ">=1.0.137"
:dep serde_yaml = ">=0.8.24"
Out[2]:
In [3]:
use std::fs
use std::collections::BTreeMap;
In [4]:
let mut map = BTreeMap::new();
map.insert("x".to_string(), 1.0);
map.insert("y".to_string(), f64::NAN);
map
Out[4]:
Serialize the above BTreeMap to a YAML string.
In [5]:
let s = serde_yaml::to_string(&map).unwrap();
println!("{s}");
Deserialize the above string back to a Rust type.
In [6]:
let deserialized_map: BTreeMap<String, f64> = serde_yaml::from_str(&s)?;
deserialized_map
Out[6]:
In [24]:
let s = fs::read_to_string("tests.yaml").unwrap();
println!("{s}");
In [25]:
let deserialized_map: BTreeMap<String, Vec<(String, String, String, f64)>> = serde_yaml::from_str(&s).unwrap();
deserialized_map
Out[25]:
In [16]:
let s = serde_yaml::to_string(&deserialized_map).unwrap();
println!("{s}");
In [26]:
use std::fs::File;
use std::io::{BufWriter, Write};
let f = File::create("out.yaml").expect("Unable to create the file out.yaml");
let mut bw = BufWriter::new(f);
serde_yaml::to_writer(bw, &deserialized_map).unwrap();
References¶
In [ ]: