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 theDeserialize
andSerialize
traits from theserde
crate, which are needed to convert YAML into a Rust struct. -
#[derive(Serialize, Deserialize)]
: This is a Rust attribute macro that automatically implements theSerialize
andDeserialize
traits for thePerson
struct. -
let yaml = r#" ... "#;
: This creates a string literal containing the YAML data. -
let person: Person = serde_yaml::from_str(yaml).unwrap();
: This uses thefrom_str
method from theserde_yaml
crate to convert the YAML string into aPerson
struct. -
println!("{:?}", person);
: This prints thePerson
struct to the console.
Helpful links
Related
More of Rust
- How to use regex with bytes in Rust?
- How to parse JSON string in Rust?
- How to match whitespace with a regex in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to declare a matrix in Rust?
- How to convert struct to JSON string in Rust?
See more codes...