From: Martin Pitt Date: Sat, 25 Sep 2021 10:22:27 +0000 (+0200) Subject: serde: Read back from file and deserialize X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=68bc0a2a4326ea89f01c90ab909095ded5e087a4;p=learn-rust.git serde: Read back from file and deserialize --- diff --git a/serde/src/main.rs b/serde/src/main.rs index 335f836..8579522 100644 --- a/serde/src/main.rs +++ b/serde/src/main.rs @@ -2,6 +2,8 @@ use std::fs; use std::error::Error; use serde::{Serialize, Deserialize}; +const DB_PATH: &str = "/tmp/contacts.json"; + #[derive(Serialize, Deserialize, Debug)] enum Social { Twitter(String), @@ -30,12 +32,19 @@ fn create_contacts() -> Result<(), Box> { let contacts = build_contacts(); let serialized = serde_json::to_string(&contacts)?; println!("serialized: {}", serialized); - let mut f = fs::File::create("/tmp/contacts.json")?; + let mut f = fs::File::create(DB_PATH)?; serde_json::to_writer_pretty(&mut f, &contacts)?; Ok(()) } +fn load_contacts() -> Result> { + let f = fs::File::open(DB_PATH)?; + Ok(serde_json::from_reader(f)?) +} + fn main() -> Result<(), Box> { create_contacts()?; + let contacts = load_contacts()?; + println!("deserialized: {:?}", contacts); Ok(()) }