4 use serde::{Serialize, Deserialize};
6 const DB_PATH: &str = "/tmp/contacts.json";
8 #[derive(Serialize, Deserialize, Debug)]
15 #[derive(Serialize, Deserialize, Debug)]
22 type Contacts = Vec<Contact>;
24 fn build_contacts() -> Contacts {
26 Contact { name: "John".to_string(), phone: 12345, social: Social::Twitter("@the_john".to_string()) },
27 Contact { name: "Mary".to_string(), phone: 9876543, social: Social::ICQ(111234) },
28 Contact { name: "Jane".to_string(), phone: 555555, social: Social::Nothing },
32 fn create_contacts() -> Result<(), Box<dyn Error>> {
33 let contacts = build_contacts();
34 let serialized = serde_json::to_string(&contacts)?;
35 log::debug!("serialized: {}", &serialized);
36 let mut f = fs::File::create(DB_PATH)?;
37 serde_json::to_writer_pretty(&mut f, &contacts)?;
41 fn load_contacts() -> Result<Contacts, Box<dyn Error>> {
42 let f = fs::File::open(DB_PATH)?;
43 Ok(serde_json::from_reader(f)?)
46 fn main() -> Result<(), Box<dyn Error>> {
47 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
49 let contacts = load_contacts()?;
50 log::info!("deserialized: {:?}", &contacts);