From 68bc0a2a4326ea89f01c90ab909095ded5e087a4 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sat, 25 Sep 2021 12:22:27 +0200 Subject: [PATCH] serde: Read back from file and deserialize --- serde/src/main.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) 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(()) } -- 2.39.5