From: Martin Pitt Date: Sat, 25 Sep 2021 10:12:45 +0000 (+0200) Subject: serde: Use error propagation X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=commitdiff_plain;h=7e0b9a5fc3356ef1d7af78ace5171af606355b1b;ds=sidebyside serde: Use error propagation --- diff --git a/serde/src/main.rs b/serde/src/main.rs index 1357100..335f836 100644 --- a/serde/src/main.rs +++ b/serde/src/main.rs @@ -1,4 +1,5 @@ use std::fs; +use std::error::Error; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] @@ -25,15 +26,16 @@ fn build_contacts() -> Contacts { ] } -fn create_contacts() { +fn create_contacts() -> Result<(), Box> { let contacts = build_contacts(); - // FIXME: Use ? and return Result - let serialized = serde_json::to_string(&contacts).unwrap(); + let serialized = serde_json::to_string(&contacts)?; println!("serialized: {}", serialized); - let mut f = fs::File::create("/tmp/contacts.json").unwrap_or_else(|e| panic!("Could not create /tmp/contacts.json: {:?}", e)); - serde_json::to_writer_pretty(&mut f, &contacts).unwrap_or_else(|e| panic!("Could not serialize contacts: {:?}", e)); + let mut f = fs::File::create("/tmp/contacts.json")?; + serde_json::to_writer_pretty(&mut f, &contacts)?; + Ok(()) } -fn main() { - create_contacts(); +fn main() -> Result<(), Box> { + create_contacts()?; + Ok(()) }