readme.rs
1 // NOTE: This file should be kept in sync with README.md
2
3 use serde_derive::{Deserialize, Serialize};
4 use std::error::Error;
5 use std::fs::File;
6
7 // Types annotated with `Serialize` can be stored as CBOR.
8 // To be able to load them again add `Deserialize`.
9 #[derive(Debug, Serialize, Deserialize)]
10 struct Mascot {
11 name: String,
12 species: String,
13 year_of_birth: u32,
14 }
15
main() -> Result<(), Box<dyn Error>>16 fn main() -> Result<(), Box<dyn Error>> {
17 let ferris = Mascot {
18 name: "Ferris".to_owned(),
19 species: "crab".to_owned(),
20 year_of_birth: 2015,
21 };
22
23 let ferris_file = File::create("examples/ferris.cbor")?;
24 // Write Ferris to the given file.
25 // Instead of a file you can use any type that implements `io::Write`
26 // like a HTTP body, database connection etc.
27 serde_cbor::to_writer(ferris_file, &ferris)?;
28
29 let tux_file = File::open("examples/tux.cbor")?;
30 // Load Tux from a file.
31 // Serde CBOR performs roundtrip serialization meaning that
32 // the data will not change in any way.
33 let tux: Mascot = serde_cbor::from_reader(tux_file)?;
34
35 println!("{:?}", tux);
36 // prints: Mascot { name: "Tux", species: "penguin", year_of_birth: 1996 }
37
38 Ok(())
39 }
40