Skip to content

Instantly share code, notes, and snippets.

@sgherbst
Last active April 28, 2021 20:04
Show Gist options
  • Select an option

  • Save sgherbst/b923f3fb9f5e1790a9f8f5020dd6ff1a to your computer and use it in GitHub Desktop.

Select an option

Save sgherbst/b923f3fb9f5e1790a9f8f5020dd6ff1a to your computer and use it in GitHub Desktop.
Modifying a serde_yaml Mapping in a function
// adapted from serde_json example: https://stackoverflow.com/a/39147207
extern crate serde_yaml;
use serde_yaml::{Value, Mapping, Number};
fn main() {
let mut map = Mapping::new();
build_mapping(&mut map, 1);
println!("{}", serde_yaml::to_string(&map).unwrap());
// ---
// key1: test
// key2:
// - a
// - b
// key3:
// x: 10
// y: 20
}
fn build_mapping(map: &mut Mapping, idx: u32) {
// made recursive to mimic real code that might generate a Mapping
if idx == 1 {
map.insert(Value::String("key1".to_string()), Value::String("test".to_string()));
build_mapping(map, idx+1);
} else if idx == 2 {
map.insert(
Value::String("key2".to_string()),
Value::Sequence(vec![
Value::String("a".to_string()),
Value::String("b".to_string()),
]),
);
build_mapping(map, idx+1);
} else {
let mut inner_map = Mapping::new();
inner_map.insert(Value::String("x".to_string()), Value::Number(Number::from(10u64)));
inner_map.insert(Value::String("y".to_string()), Value::Number(Number::from(20u64)));
map.insert(Value::String("key3".to_string()), Value::Mapping(inner_map));
}
}
@sgherbst
Copy link
Author

The above code can be directly run in the Rust Playground: https://play.rust-lang.org

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment