From 80e4d9aff6de0cdeaedc8db269a18c6da91d0239 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Mon, 23 Aug 2021 14:02:33 +0200 Subject: [PATCH] File reading and error handling using ? --- src/main.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/main.rs b/src/main.rs index 973bb2e..441cc79 100644 --- a/src/main.rs +++ b/src/main.rs @@ -69,6 +69,13 @@ fn test_hashmaps() { println!("collect_scores after rebuilding with doubling: {:?}", collect_scores); } +fn read_file(path: &str) -> Result { + let mut s = String::new(); + File::open(path)? + .read_to_string(&mut s)?; + Ok(s) +} + fn test_files() { if let Ok(mut f) = File::open("Cargo.toml") { let mut contents = String::new(); @@ -95,6 +102,12 @@ fn test_files() { panic!("Could not read file: {:?}", e); }); println!("successfully opened Cargo.toml with unwrap_or_else: {:?}, contents {} bytes:\n{}\n----------", f, len, contents); + + // using the '?' operator + match read_file("Cargo.toml") { + Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s), + Err(e) => println!("Could not open Cargo.toml: {:?}", e) + } } fn main() { -- 2.39.5