rustHow to convert YAML to struct in Rust
YAML (YAML Ain't Markup Language) is a human-readable data serialization language that can be used to convert data into a variety of data structures. In Rust, the serde_yaml crate can be used to convert YAML into a Rust struct.
Example code:
use serde::{Deserialize, Serialize};
use serde_yaml;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
fn main() {
let yaml = r#"
name: John
age: 30
"#;
let person: Person = serde_yaml::from_str(yaml).unwrap();
println!("{:?}", person);
}
Output example
Person { name: "John", age: 30 }
Code parts with detailed ## Explanation
-
use serde::{Deserialize, Serialize};: This imports theDeserializeandSerializetraits from theserdecrate, which are needed to convert YAML into a Rust struct. -
#[derive(Serialize, Deserialize)]: This is a Rust attribute macro that automatically implements theSerializeandDeserializetraits for thePersonstruct. -
let yaml = r#" ... "#;: This creates a string literal containing the YAML data. -
let person: Person = serde_yaml::from_str(yaml).unwrap();: This uses thefrom_strmethod from theserde_yamlcrate to convert the YAML string into aPersonstruct. -
println!("{:?}", person);: This prints thePersonstruct to the console.
Helpful links
Related
More of Rust
- How to use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...