diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index 13d2724..83018b5 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -9,14 +9,14 @@ // Execute `rustlings hint errors1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +use std::fmt::Error; -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { if name.is_empty() { // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".to_string()) } else { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } } diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index d86f326..ea09376 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -19,14 +19,12 @@ // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a // hint. -// 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; - let qty = item_quantity.parse::(); + let qty = item_quantity.parse::()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index d42d3b1..d831801 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -7,21 +7,19 @@ // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +use std::{fmt::Error, num::ParseIntError}; -use std::num::ParseIntError; - -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; let cost = total_cost(pretend_user_input)?; if cost > tokens { - println!("You can't afford that many!"); + Ok(println!("You can't afford that many!")) } else { tokens -= cost; - println!("You now have {} tokens.", tokens); + Ok(println!("You now have {} tokens.", tokens)) } } diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index e04bff7..9b963f3 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -16,8 +14,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { - // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) + if value < 0 { + Err(CreationError::Negative) + } else if value == 0 { + Err(CreationError::Zero) + } else { + Ok(PositiveNonzeroInteger(value as u64)) + } } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 92461a7..e4363f8 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -22,14 +22,13 @@ // Execute `rustlings hint errors5` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::error; +use std::error::Error; use std::fmt; use std::num::ParseIntError; // TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), Box> { +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 aaf0948..6b95d44 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -9,8 +9,6 @@ // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::num::ParseIntError; // This is a custom error type that we will be using in `parse_pos_nonzero()`. @@ -25,14 +23,21 @@ impl ParsePosNonzeroError { ParsePosNonzeroError::Creation(err) } // TODO: add another error conversion function here. - // fn from_parseint... + fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError { + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) -> Result { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); - PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) + match s.parse() { + Ok(x) => match PositiveNonzeroInteger::new(x) { + Ok(x) => Ok(x), + Err(err) => Err(ParsePosNonzeroError::from_creation(err)), + }, + Err(err) => Err(ParsePosNonzeroError::from_parseint(err)), + } } // Don't change anything below this line. diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index 35c1d2f..1f4fa4a 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -6,9 +6,7 @@ // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a // hint. -// 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 074cd93..b0cc651 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -6,14 +6,12 @@ // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a // hint. -// 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/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs index 80829ea..51b1ef5 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -11,17 +11,15 @@ // Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a // hint. -// 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(); // 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"), 3); + basket.insert(String::from("mango"), 5); basket } diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index a592569..7562d31 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -14,8 +14,6 @@ // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::collections::HashMap; #[derive(Hash, PartialEq, Eq)] @@ -37,9 +35,11 @@ fn fruit_basket(basket: &mut HashMap) { ]; for fruit in fruit_kinds { - // TODO: Insert new fruits if they are not already present in the - // basket. Note that you are not allowed to put any type of fruit that's - // already present! + if basket.get(&fruit).is_some() { + continue; + } + + basket.insert(fruit, 5); } } @@ -81,7 +81,7 @@ mod tests { let count = basket.values().sum::(); assert!(count > 11); } - + #[test] fn all_fruit_types_in_basket() { let mut basket = get_fruit_basket(); diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index 08e977c..5e61d9f 100644 --- a/exercises/hashmaps/hashmaps3.rs +++ b/exercises/hashmaps/hashmaps3.rs @@ -14,8 +14,6 @@ // Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - use std::collections::HashMap; // A structure to store the goal details of a team. @@ -34,11 +32,28 @@ fn build_scores_table(results: String) -> HashMap { let team_1_score: u8 = v[2].parse().unwrap(); let team_2_name = v[1].to_string(); let team_2_score: u8 = v[3].parse().unwrap(); - // TODO: Populate the scores table with details extracted from the - // current line. Keep in mind that goals scored by team_1 - // will be the number of goals conceded from team_2, and similarly - // goals scored by team_2 will be the number of goals conceded by - // team_1. + + if let Some(entry) = scores.get_mut(&team_1_name) { + entry.goals_scored += team_1_score; + entry.goals_conceded += team_2_score; + } else { + let team = Team { + goals_scored: team_1_score, + goals_conceded: team_2_score, + }; + scores.insert(team_1_name, team); + } + + if let Some(entry) = scores.get_mut(&team_2_name) { + entry.goals_scored += team_2_score; + entry.goals_conceded += team_1_score; + } else { + let team = Team { + goals_scored: team_2_score, + goals_conceded: team_1_score, + }; + scores.insert(team_2_name, team); + } } scores } diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs index 9eb5a48..a26f5c4 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/modules/modules1.rs @@ -3,15 +3,13 @@ // Execute `rustlings hint modules1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - mod sausage_factory { // Don't let anybody outside of this module see this! fn get_secret_recipe() -> String { String::from("Ginger") } - fn make_sausage() { + pub fn make_sausage() { get_secret_recipe(); println!("sausage!"); } diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs index 0415454..f5bd7cc 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -7,12 +7,10 @@ // Execute `rustlings hint modules2` or use the `hint` watch subcommand for a // hint. -// 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 f2bb050..f14c53e 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,10 +8,7 @@ // Execute `rustlings hint modules3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - -// TODO: Complete this use statement -use ??? +use std::time::*; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs index e131b48..be048c2 100644 --- a/exercises/options/options1.rs +++ b/exercises/options/options1.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint options1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - // This function returns how much icecream there is left in the fridge. // If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them // all, so there'll be no more left :( @@ -12,8 +10,11 @@ fn maybe_icecream(time_of_day: u16) -> Option { // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a // value of 0 The Option output should gracefully handle cases where // time_of_day > 23. - // TODO: Complete the function body - remember to return an Option! - ??? + match time_of_day { + 0..=10 => Some(5 as u16), + 11..=24 => Some(0 as u16), + _ => None, + } } #[cfg(test)] @@ -31,9 +32,8 @@ mod tests { #[test] fn raw_value() { - // TODO: Fix this test. How do you get at the value contained in the - // Option? - let icecreams = maybe_icecream(12); - assert_eq!(icecreams, 5); + if let Some(icecreams) = maybe_icecream(12) { + assert_eq!(icecreams, 0); + } } } diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index 4d998e7..cbf281f 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint options2` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] @@ -13,7 +11,7 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { + if let Some(word) = optional_target { assert_eq!(word, target); } } @@ -32,7 +30,7 @@ mod tests { // TODO: make this a while let statement - remember that vector.pop also // adds another layer of Option. You can stack `Option`s into // while let and if let. - integer = optional_integers.pop() { + while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, cursor); cursor -= 1; } diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs index 23c15ea..bca3cff 100644 --- a/exercises/options/options3.rs +++ b/exercises/options/options3.rs @@ -3,8 +3,6 @@ // Execute `rustlings hint options3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - struct Point { x: i32, y: i32, @@ -14,7 +12,7 @@ fn main() { let y: Option = Some(Point { x: 100, y: 200 }); match y { - Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), + Some(ref p) => println!("Co-ordinates are {},{} ", p.x, p.y), _ => panic!("no match!"), } y; // Fix without deleting this line. diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index 29925ca..66e2bd6 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -20,8 +20,6 @@ // // No hints this time! -// I AM NOT DONE - pub enum Command { Uppercase, Trim, @@ -31,12 +29,17 @@ pub enum Command { mod my_module { use super::Command; - // TODO: Complete the function signature! - pub fn transformer(input: ???) -> ??? { - // TODO: Complete the output declaration! - let mut output: ??? = vec![]; + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut output: Vec = vec![]; for (string, command) in input.iter() { - // TODO: Complete the function body. You can do it! + match command { + Command::Uppercase => output.push(string.to_uppercase()), + Command::Trim => output.push(string.trim().to_string()), + Command::Append(x) => { + let suffix = "bar".repeat(*x); + output.push(String::from(string) + &suffix); + } + } } output } @@ -44,8 +47,7 @@ mod my_module { #[cfg(test)] mod tests { - // TODO: What do we need to import to have `transformer` in scope? - use ???; + use super::my_module::transformer; use super::Command; #[test] diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index f50e1fa..c321291 100644 --- a/exercises/strings/strings1.rs +++ b/exercises/strings/strings1.rs @@ -5,13 +5,11 @@ // Execute `rustlings hint strings1` or use the `hint` watch subcommand for a // hint. -// 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 4d95d16..ca16ea3 100644 --- a/exercises/strings/strings2.rs +++ b/exercises/strings/strings2.rs @@ -5,11 +5,9 @@ // Execute `rustlings hint strings2` or use the `hint` watch subcommand for a // hint. -// 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."); diff --git a/exercises/strings/strings3.rs b/exercises/strings/strings3.rs index b29f932..55006fa 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -3,21 +3,16 @@ // Execute `rustlings hint strings3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - fn trim_me(input: &str) -> String { - // TODO: Remove whitespace from both ends of a string! - ??? + String::from(input.trim()) } fn compose_me(input: &str) -> String { - // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? + String::from(input) + " world!" } fn replace_me(input: &str) -> String { - // TODO: Replace "cars" in the string with "balloons"! - ??? + input.replace("cars", "balloons") } #[cfg(test)] @@ -39,7 +34,13 @@ mod tests { #[test] fn replace_a_string() { - assert_eq!(replace_me("I think cars are cool"), "I think balloons are cool"); - assert_eq!(replace_me("I love to look at cars"), "I love to look at balloons"); + assert_eq!( + replace_me("I think cars are cool"), + "I think balloons are cool" + ); + assert_eq!( + replace_me("I love to look at cars"), + "I love to look at balloons" + ); } } diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs index e8c54ac..9c2a0c7 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -7,8 +7,6 @@ // // No hints this time! -// 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/traits/traits1.rs b/exercises/traits/traits1.rs index 37dfcbf..4ea8c36 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -7,14 +7,14 @@ // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } impl AppendBar for String { - // TODO: Implement `AppendBar` for type `String`. + fn append_bar(self) -> Self { + self + "Bar" + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 3e35f8e..0676784 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -8,13 +8,17 @@ // // Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } -// TODO: Implement trait `AppendBar` for a vector of strings. +impl AppendBar for Vec { + fn append_bar(self) -> Self { + let mut list = self; + list.push(String::from("Bar")); + list + } +} #[cfg(test)] mod tests { diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 4e2b06b..7b75874 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/traits/traits3.rs @@ -8,10 +8,10 @@ // Execute `rustlings hint traits3` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE - pub trait Licensed { - fn licensing_info(&self) -> String; + fn licensing_info(&self) -> String { + String::from("Some information") + } } struct SomeSoftware { diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs index 4bda3e5..575a684 100644 --- a/exercises/traits/traits4.rs +++ b/exercises/traits/traits4.rs @@ -23,7 +23,7 @@ impl Licensed for SomeSoftware {} impl Licensed for OtherSoftware {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { +fn compare_license_types(software: impl Licensed, software_two: impl Licensed) -> bool { software.licensing_info() == software_two.licensing_info() }