From 7e0b9a5fc3356ef1d7af78ace5171af606355b1b Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sat, 25 Sep 2021 12:12:45 +0200 Subject: [PATCH] serde: Use error propagation --- serde/src/main.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) 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(()) } -- 2.39.5