From 58fc67525bcd8fa5ebac0215992b39b866b24bd7 Mon Sep 17 00:00:00 2001 From: Yuhua Mai <yuhua@urbandoor.com> Date: Sat, 16 May 2020 00:13:23 -0700 Subject: [PATCH] More exercises --- .gitignore | 2 ++ exercises/clippy/clippy1.rs | 3 +-- exercises/clippy/clippy2.rs | 3 +-- exercises/error_handling/errors1.rs | 9 ++++----- exercises/error_handling/errors2.rs | 3 +-- exercises/error_handling/errors3.rs | 5 +++-- exercises/error_handling/errorsn.rs | 11 +++++------ exercises/error_handling/option1.rs | 5 ++++- exercises/error_handling/result1.rs | 9 +++++++-- exercises/option/option1.rs | 9 ++++----- exercises/option/option2.rs | 5 ++--- 11 files changed, 34 insertions(+), 30 deletions(-) diff --git a/.gitignore b/.gitignore index de87c1e..5eb4972 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ target/ *.pdb exercises/clippy/Cargo.toml exercises/clippy/Cargo.lock + +.idea diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs index 2b4c635..862f71f 100644 --- a/exercises/clippy/clippy1.rs +++ b/exercises/clippy/clippy1.rs @@ -4,12 +4,11 @@ // // Execute `rustlings hint clippy1` for hints :) -// I AM NOT DONE fn main() { let x = 1.2331f64; let y = 1.2332f64; - if y != x { + if (y - x).abs() > 0.0001 { println!("Success!"); } } diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs index 37af9ed..ec6af9e 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -1,12 +1,11 @@ // clippy2.rs // Make me compile! Execute `rustlings hint clippy2` for hints :) -// I AM NOT DONE fn main() { let mut res = 42; let option = Some(12); - for x in option { + if let Some(x) = option { res += x; } println!("{}", res); diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 9c24d85..b36c1ec 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -6,14 +6,13 @@ // this function to have. // Execute `rustlings hint errors1` for hints! -// I AM NOT DONE -pub fn generate_nametag_text(name: String) -> Option<String> { +pub fn generate_nametag_text(name: String) -> Result<String, String> { if name.len() > 0 { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } else { // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".to_string()) } } @@ -28,7 +27,7 @@ mod tests { fn generates_nametag_text_for_a_nonempty_name() { assert_eq!( generate_nametag_text("Beyoncé".into()), - Some("Hi! My name is Beyoncé".into()) + Ok("Hi! My name is Beyoncé".into()) ); } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index aad3a93..cfc8537 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -16,14 +16,13 @@ // There are at least two ways to implement this that are both correct-- but // one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways. -// I AM NOT DONE use std::num::ParseIntError; pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::<i32>(); + let qty = item_quantity.parse::<i32>()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index 460ac5c..88d8f32 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -4,11 +4,10 @@ // Why not? What should we do to fix it? // Execute `rustlings hint errors3` for hints! -// I AM NOT DONE use std::num::ParseIntError; -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; @@ -20,6 +19,8 @@ fn main() { tokens -= cost; println!("You now have {} tokens.", tokens); } + + Ok(()) } pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> { diff --git a/exercises/error_handling/errorsn.rs b/exercises/error_handling/errorsn.rs index 3079943..9c0e091 100644 --- a/exercises/error_handling/errorsn.rs +++ b/exercises/error_handling/errorsn.rs @@ -15,19 +15,18 @@ // // Execute `rustlings hint errorsn` for hints :) -// I AM NOT DONE use std::error; use std::fmt; use std::io; // PositiveNonzeroInteger is a struct defined below the tests. -fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, ???> { +fn read_and_validate(b: &mut dyn io::BufRead) -> Result<PositiveNonzeroInteger, Box<dyn error::Error>> { let mut line = String::new(); - b.read_line(&mut line); - let num: i64 = line.trim().parse(); - let answer = PositiveNonzeroInteger::new(num); - answer + b.read_line(&mut line)?; + let num: i64 = line.trim().parse()?; + let answer: PositiveNonzeroInteger = PositiveNonzeroInteger::new(num)?; + Ok(answer) } // This is a test helper function that turns a &str into a BufReader. diff --git a/exercises/error_handling/option1.rs b/exercises/error_handling/option1.rs index 5d81b15..00c6d6b 100644 --- a/exercises/error_handling/option1.rs +++ b/exercises/error_handling/option1.rs @@ -12,7 +12,10 @@ pub fn pop_too_much() -> bool { let last = list.pop().unwrap(); println!("The last item in the list is {:?}", last); - let second_to_last = list.pop().unwrap(); + let second_to_last = match list.pop() { + Some(i) => i, + None => 0 + }; println!( "The second-to-last item in the list is {:?}", second_to_last diff --git a/exercises/error_handling/result1.rs b/exercises/error_handling/result1.rs index b978001..25857cb 100644 --- a/exercises/error_handling/result1.rs +++ b/exercises/error_handling/result1.rs @@ -1,7 +1,6 @@ // result1.rs // Make this test pass! Execute `rustlings hint result1` for hints :) -// I AM NOT DONE #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -14,7 +13,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> { - Ok(PositiveNonzeroInteger(value as u64)) + if value == 0 { + Err(CreationError::Zero) + } else if value < 0 { + Err(CreationError::Negative) + } else { + Ok(PositiveNonzeroInteger(value as u64)) + } } } diff --git a/exercises/option/option1.rs b/exercises/option/option1.rs index 51c39f5..852911e 100644 --- a/exercises/option/option1.rs +++ b/exercises/option/option1.rs @@ -1,7 +1,6 @@ // option1.rs // Make me compile! Execute `rustlings hint option1` for hints -// I AM NOT DONE // you can modify anything EXCEPT for this function's sig fn print_number(maybe_number: Option<u16>) { @@ -9,15 +8,15 @@ fn print_number(maybe_number: Option<u16>) { } fn main() { - print_number(13); - print_number(99); + print_number(Some(13)); + print_number(Some(99)); - let mut numbers: [Option<u16>; 5]; + let mut numbers: [Option<u16>; 5] = [None; 5]; for iter in 0..5 { let number_to_add: u16 = { ((iter * 5) + 2) / (4 * 16) }; - numbers[iter] = number_to_add; + numbers[iter as usize] = Some(number_to_add); } } diff --git a/exercises/option/option2.rs b/exercises/option/option2.rs index a55f734..c77c80f 100644 --- a/exercises/option/option2.rs +++ b/exercises/option/option2.rs @@ -1,12 +1,11 @@ // option2.rs // Make me compile! Execute `rustlings hint option2` for hints -// I AM NOT DONE fn main() { let optional_value = Some(String::from("rustlings")); // Make this an if let statement whose value is "Some" type - value = optional_value { + if let Some(value) = optional_value { println!("the value of optional value is: {}", value); } else { println!("The optional value doesn't contain anything!"); @@ -19,7 +18,7 @@ fn main() { // make this a while let statement - remember that vector.pop also adds another layer of Option<T> // You can stack `Option<T>`'s into while let and if let - value = optional_values_vec.pop() { + while let Some(Some(value)) = optional_values_vec.pop() { println!("current value: {}", value); } }