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 theSerialize
andDeserialize
traits from theserde
crate. 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 theSerialize
andDeserialize
traits for thePerson
struct.serde_yaml::to_string(&person).unwrap()
: This uses theserde_yaml
crate to serialize theperson
struct into a YAML string.serde_yaml::from_str(&serialized).unwrap()
: This uses theserde_yaml
crate to deserialize the YAML string into aPerson
struct.
Helpful links
Related
More of Rust
- How to replace strings using Rust regex?
- How to parse JSON string in Rust?
- How to compile a regex in Rust?
- How to perform matrix operations in Rust?
- How to convert struct to JSON string in Rust?
- How to add matrices in Rust?
- How to replace a capture group using Rust regex?
- How to multiply matrices in Rust?
- How to use regex builder in Rust?
- Hashshet example in Rust
See more codes...