From 8239cc2be624d6a6cf040018b56fadbab282c3c9 Mon Sep 17 00:00:00 2001 From: Stanislav Pankrashin Date: Wed, 22 Jun 2022 14:58:51 +1200 Subject: [PATCH] did some more --- exercises/collections/hashmap1.rs | 6 +++--- exercises/collections/hashmap2.rs | 5 +++-- exercises/collections/vec1.rs | 4 +--- exercises/collections/vec2.rs | 3 +-- exercises/error_handling/errors1.rs | 9 +++------ exercises/error_handling/errors2.rs | 10 ++++++++-- exercises/error_handling/errors3.rs | 9 ++++++--- exercises/error_handling/errors4.rs | 9 +++++++-- exercises/error_handling/errors5.rs | 4 +--- exercises/error_handling/errors6.rs | 16 +++++++++++++--- exercises/generics/generics1.rs | 4 +--- exercises/generics/generics2.rs | 10 ++++------ exercises/generics/generics3.rs | 10 ++++------ exercises/modules/modules2.rs | 6 ++---- exercises/modules/modules3.rs | 4 +--- exercises/quiz2.rs | 22 ++++++++++------------ exercises/strings/strings1.rs | 4 +--- exercises/strings/strings2.rs | 4 +--- 18 files changed, 70 insertions(+), 69 deletions(-) diff --git a/exercises/collections/hashmap1.rs b/exercises/collections/hashmap1.rs index 64b5a7f3..fd36700c 100644 --- a/exercises/collections/hashmap1.rs +++ b/exercises/collections/hashmap1.rs @@ -11,17 +11,17 @@ // Execute the command `rustlings hint hashmap1` if you need // hints. -// I AM NOT DONE - use std::collections::HashMap; fn fruit_basket() -> HashMap { - let mut basket = // TODO: declare your hash map here. + let mut basket = HashMap::new();// TODO: declare your hash map here. // Two bananas are already given for you :) basket.insert(String::from("banana"), 2); // TODO: Put more fruits in your basket here. + basket.insert(String::from("apple"), 2); + basket.insert(String::from("mango"), 1); basket } diff --git a/exercises/collections/hashmap2.rs b/exercises/collections/hashmap2.rs index 0abe19ab..849b00a9 100644 --- a/exercises/collections/hashmap2.rs +++ b/exercises/collections/hashmap2.rs @@ -12,8 +12,6 @@ // Execute the command `rustlings hint hashmap2` if you need // hints. -// I AM NOT DONE - use std::collections::HashMap; #[derive(Hash, PartialEq, Eq)] @@ -38,6 +36,9 @@ fn fruit_basket(basket: &mut HashMap) { // TODO: Put new fruits if not already present. Note that you // are not allowed to put any type of fruit that's already // present! + if basket.get(&fruit) == None { + basket.insert(fruit, 1); + } } } diff --git a/exercises/collections/vec1.rs b/exercises/collections/vec1.rs index b144fb94..68287fe2 100644 --- a/exercises/collections/vec1.rs +++ b/exercises/collections/vec1.rs @@ -4,11 +4,9 @@ // Make me compile and pass the test! // Execute the command `rustlings hint vec1` if you need hints. -// I AM NOT DONE - fn array_and_vec() -> ([i32; 4], Vec) { let a = [10, 20, 30, 40]; // a plain array - let v = // TODO: declare your vector here with the macro for vectors + let v = vec![10, 20, 30, 40];// TODO: declare your vector here with the macro for vectors (a, v) } diff --git a/exercises/collections/vec2.rs b/exercises/collections/vec2.rs index 6595e401..51f393c3 100644 --- a/exercises/collections/vec2.rs +++ b/exercises/collections/vec2.rs @@ -7,12 +7,11 @@ // Execute the command `rustlings hint vec2` if you need // hints. -// I AM NOT DONE - fn vec_loop(mut v: Vec) -> Vec { for i in v.iter_mut() { // TODO: Fill this up so that each element in the Vec `v` is // multiplied by 2. + *i = *i * 2; } // At this point, `v` should be equal to [4, 8, 12, 16, 20]. diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index c417fb26..0e31ecb0 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -5,14 +5,11 @@ // construct to `Option` that can be used to express error conditions. Let's use it! // Execute `rustlings hint errors1` for hints! -// I AM NOT DONE - -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { 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(String::from("`name` was empty; it must be nonempty.")) } } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index aad3a93f..0d901062 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -16,14 +16,20 @@ // 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 { let processing_fee = 1; let cost_per_item = 5; + // method one + //let mut qty = item_quantity.parse::()?; + + // method two let qty = item_quantity.parse::(); + let mut qty = match qty { + Ok(number) => number, + Err(e) => return Err(e), + }; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index 460ac5c4..f5a5a2df 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -4,15 +4,18 @@ // 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() { let mut tokens = 100; let pretend_user_input = "8"; - let cost = total_cost(pretend_user_input)?; + let cost = total_cost(pretend_user_input); + + let mut cost = match cost { + Ok(number) => number, + Err(e) => panic!(e), + }; if cost > tokens { println!("You can't afford that many!"); diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index 0685c374..8b2a2efe 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -1,8 +1,6 @@ // errors4.rs // Make this test pass! Execute `rustlings hint errors4` for hints :) -// I AM NOT DONE - #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -14,6 +12,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { + + if value == 0 { + return Err(CreationError::Zero) + } else if value < 0 { + return Err(CreationError::Negative) + } + Ok(PositiveNonzeroInteger(value as u64)) } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 365a8691..66889a33 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -4,14 +4,12 @@ // It won't compile right now! Why? // Execute `rustlings hint errors5` for hints! -// I AM NOT DONE - use std::error; use std::fmt; use std::num::ParseIntError; // TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), ParseIntError> { +fn main() -> Result<(), Box> { let pretend_user_input = "42"; let x: i64 = pretend_user_input.parse()?; println!("output={:?}", PositiveNonzeroInteger::new(x)?); diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs index 847a049a..16eb7bf5 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -8,8 +8,6 @@ // Make these tests pass! Execute `rustlings hint errors6` for hints :) -// I AM NOT DONE - use std::num::ParseIntError; // This is a custom error type that we will be using in `parse_pos_nonzero()`. @@ -21,6 +19,13 @@ enum ParsePosNonzeroError { impl ParsePosNonzeroError { // TODO: add another error conversion function here. + fn from_creation(err: CreationError) -> ParsePosNonzeroError { + ParsePosNonzeroError::Creation(err) + } + + fn from_parsing(err: ParseIntError) -> ParsePosNonzeroError { + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) @@ -28,7 +33,12 @@ fn parse_pos_nonzero(s: &str) { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); + let x: Result = s.parse(); + let mut x: i64 = match x { + Ok(number) => number, + Err(e) => return Err(ParsePosNonzeroError::ParseInt(e)), + }; + PositiveNonzeroInteger::new(x) .map_err(ParsePosNonzeroError::from_creation) } diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index f93e64a0..59432e08 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -3,9 +3,7 @@ // Execute `rustlings hint generics1` for hints! -// I AM NOT DONE - fn main() { - let mut shopping_list: Vec = Vec::new(); + let mut shopping_list: Vec<&str> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index 1501529c..8c6a5100 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -3,14 +3,12 @@ // Execute `rustlings hint generics2` for hints! -// I AM NOT DONE - -struct Wrapper { - value: u32, +struct Wrapper { + value: T, } -impl Wrapper { - pub fn new(value: u32) -> Self { +impl Wrapper { + pub fn new(value: T) -> Self { Wrapper { value } } } diff --git a/exercises/generics/generics3.rs b/exercises/generics/generics3.rs index 64dd9bc1..21dd9324 100644 --- a/exercises/generics/generics3.rs +++ b/exercises/generics/generics3.rs @@ -10,15 +10,13 @@ // Execute 'rustlings hint generics3' for hints! -// I AM NOT DONE - -pub struct ReportCard { - pub grade: f32, +pub struct ReportCard { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl ReportCard { pub fn print(&self) -> String { format!("{} ({}) - achieved a grade of {}", &self.student_name, &self.student_age, &self.grade) @@ -46,7 +44,7 @@ mod tests { fn generate_alphabetic_report_card() { // TODO: Make sure to change the grade here after you finish the exercise. let report_card = ReportCard { - grade: 2.1, + grade: "A+", student_name: "Gary Plotter".to_string(), student_age: 11, }; diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs index 87f0c458..8d25567b 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -3,13 +3,11 @@ // 'use' and 'as' keywords. Fix these 'use' statements to make the code compile. // Make me compile! Execute `rustlings hint modules2` for hints :) -// I AM NOT DONE - mod delicious_snacks { // TODO: Fix these use statements - use self::fruits::PEAR as ??? - use self::veggies::CUCUMBER as ??? + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; mod fruits { pub const PEAR: &'static str = "Pear"; diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs index 8eed77df..a28bd9eb 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -5,10 +5,8 @@ // from the std::time module. Bonus style points if you can do it with one line! // Make me compile! Execute `rustlings hint modules3` for hints :) -// I AM NOT DONE - // TODO: Complete this use statement -use ??? +use std::time::{UNIX_EPOCH, SystemTime}; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index de0dce95..37c33a53 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -7,8 +7,6 @@ // you think each value is. That is, add either `string_slice` or `string` // before the parentheses on each line. If you're right, it will compile! -// I AM NOT DONE - fn string_slice(arg: &str) { println!("{}", arg); } @@ -17,14 +15,14 @@ fn string(arg: String) { } fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); + string_slice("blue"); + string("red".to_string()); + string(String::from("hi")); + string("rust is fun!".to_owned()); + string("nice weather".into()); + string(format!("Interpolation {}", "Station")); + string_slice(&String::from("abc")[0..1]); + string_slice(" hello there ".trim()); + string("Happy Monday!".to_string().replace("Mon", "Tues")); + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); } diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index 80902444..e43c88a4 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -2,13 +2,11 @@ // Make me compile without changing the function signature! // Execute `rustlings hint strings1` for hints ;) -// I AM NOT DONE - fn main() { let answer = current_favorite_color(); println!("My current favorite color is {}", answer); } fn current_favorite_color() -> String { - "blue" + String::from("blue") } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 5a2ce74a..a048f882 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -2,11 +2,9 @@ // Make me compile without changing the function signature! // Execute `rustlings hint strings2` for hints :) -// I AM NOT DONE - fn main() { let word = String::from("green"); // Try not changing this line :) - if is_a_color_word(word) { + if is_a_color_word(&word) { println!("That is a color word I know!"); } else { println!("That is not a color word I know.");