From a1fc1827121d3c313b21fe04c02f543d827f321d Mon Sep 17 00:00:00 2001 From: Andrew Johnson Date: Thu, 24 May 2018 18:47:25 -0600 Subject: [PATCH] debugging result --- Chapter09/.gitignore | 1 + Chapter09/Cargo.toml | 4 +++ Chapter09/debugging_result.rs | 50 +++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 Chapter09/.gitignore create mode 100644 Chapter09/debugging_result.rs diff --git a/Chapter09/.gitignore b/Chapter09/.gitignore new file mode 100644 index 0000000..b881d2f --- /dev/null +++ b/Chapter09/.gitignore @@ -0,0 +1 @@ +data.txt diff --git a/Chapter09/Cargo.toml b/Chapter09/Cargo.toml index fec0c89..562f5b3 100644 --- a/Chapter09/Cargo.toml +++ b/Chapter09/Cargo.toml @@ -67,3 +67,7 @@ path = "performance_exponential.rs" [[bin]] name = "performance_reference" path = "performance_reference.rs" + +[[bin]] +name = "debugging_result" +path = "debugging_result.rs" diff --git a/Chapter09/debugging_result.rs b/Chapter09/debugging_result.rs new file mode 100644 index 0000000..e0cfbb2 --- /dev/null +++ b/Chapter09/debugging_result.rs @@ -0,0 +1,50 @@ +fn expect_1or2or_other(n: u64) -> Option { + match n { + 1|2 => Some(n), + _ => None + } +} + +fn expect_1or2or_error(n: u64) -> Result { + match n { + 1|2 => Ok(n), + _ => Err(()) + } +} + +fn mixed_1or2() -> Result<(),()> { + expect_1or2or_other(1); + expect_1or2or_other(2); + expect_1or2or_other(3); + + expect_1or2or_error(1)?; + expect_1or2or_error(2)?; + expect_1or2or_error(3).unwrap_or(222); + + Ok(()) +} + +use std::fs::File; +use std::io::prelude::*; +use std::io; + +fn lots_of_io() -> io::Result<()> { + { + let mut file = File::create("data.txt")?; + file.write_all(b"data\ndata\ndata")?; + } + { + let mut file = File::open("data.txt")?; + let mut data = String::new(); + file.read_to_string(&mut data)?; + println!("{}", data); + } + + Ok(()) +} + +fn main() { + mixed_1or2().expect("mixed 1 or 2 is OK."); + + lots_of_io().expect("lots of io is OK."); +}