rustYAML serde example in Rust
YAML is a popular data serialization format that is used to store data in a human-readable format. Rust provides a library called serde_yaml which can be used to serialize and deserialize YAML data.
Example code:
use serde::{Deserialize, Serialize};
use serde_yaml;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
}
fn main() {
let person = Person {
name: "John".to_string(),
age: 30,
};
let serialized = serde_yaml::to_string(&person).unwrap();
println!("Serialized: {}", serialized);
let deserialized: Person = serde_yaml::from_str(&serialized).unwrap();
println!("Deserialized: {:?}", deserialized);
}
Output example
Serialized: age: 30
name: John
Deserialized: Person { name: "John", age: 30 }
Code parts with detailed ## Explanation
use serde::{Deserialize, Serialize};: This imports theSerializeandDeserializetraits from theserdecrate. These traits are used to define the data structure that will be serialized and deserialized.#[derive(Serialize, Deserialize)]: This is a Rust macro that automatically implements theSerializeandDeserializetraits for thePersonstruct.serde_yaml::to_string(&person).unwrap(): This uses theserde_yamlcrate to serialize thepersonstruct into a YAML string.serde_yaml::from_str(&serialized).unwrap(): This uses theserde_yamlcrate to deserialize the YAML string into aPersonstruct.
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...