Created
April 28, 2021 21:47
-
-
Save sgherbst/10392864cb183e718f5b098777d88f80 to your computer and use it in GitHub Desktop.
Returning a serde_yaml Mapping for building a nested Mapping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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: 12 | |
| // y: 34 | |
| } | |
| fn build_mapping(map: &mut Mapping, idx: u32) { | |
| 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 { | |
| map.insert( | |
| Value::String("key3".to_string()), | |
| Value::Mapping(build_inner_map(12, 34)) | |
| ); | |
| } | |
| } | |
| fn build_inner_map(val1: u32, val2: u32) -> Mapping { | |
| let mut inner_map = Mapping::new(); | |
| inner_map.insert(Value::String("x".to_string()), Value::Number(Number::from(val1))); | |
| inner_map.insert(Value::String("y".to_string()), Value::Number(Number::from(val2))); | |
| return inner_map; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment