X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=blobdiff_plain;f=src%2Fmain.rs;h=c07c4051165861365a2176a3c1edec6957d16903;hp=973bb2e6c8a3ff790ed25a03f690ea48c6a29084;hb=1d259ded66e8edc398867ac80b0c138abe707ea0;hpb=56e1367f9394b43c2c8f1e4119df70f02d57ba75 diff --git a/src/main.rs b/src/main.rs index 973bb2e..c07c405 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,7 +2,7 @@ mod word_utils; use std::collections::HashMap; use std::io::{prelude::*, ErrorKind}; -use std::fs::File; +use std::fs::{self, File}; use word_utils::{first_word, second_word}; @@ -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,18 @@ 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) + } + + // using std API + match fs::read_to_string("Cargo.toml") { + Ok(s) => println!("Cargo.toml contents:\n{}\n-------------", s), + Err(e) => println!("Could not open Cargo.toml: {:?}", e) + } } fn main() {