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 match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace all using regex in Rust?
- How to replace all matches using Rust regex?
- How to borrow from vector in Rust
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
See more codes...