diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index e6a9d114..2df7c524 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -3,25 +3,20 @@ // and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - // Obtain the number of bytes (not characters) in the given argument. -// TODO: Add the AsRef trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { +fn byte_counter(arg: T) -> usize where T: AsRef { arg.as_ref().as_bytes().len() } // Obtain the number of characters (not bytes) in the given argument. -// TODO: Add the AsRef trait appropriately as a trait bound. -fn char_counter(arg: T) -> usize { +fn char_counter(arg: T) -> usize where T: AsRef { arg.as_ref().chars().count() } // Squares a number using as_mut(). -// TODO: Add the appropriate trait bound. -fn num_sq(arg: &mut T) { - // TODO: Implement the function body. - ??? +fn num_sq(arg: &mut T) where T: AsMut { + let v = arg.as_mut(); + *v = (*v) * (*v) } #[cfg(test)] diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index 6c272c3b..f75edb62 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -35,10 +35,34 @@ impl Default for Person { // If while parsing the age, something goes wrong, then return the default of Person // Otherwise, then return an instantiated Person object with the results -// I AM NOT DONE - impl From<&str> for Person { fn from(s: &str) -> Person { + if s.is_empty() { + return Default::default(); + } + let vals = s.split(","); + let mut idx = 0; + let mut name: &str = ""; + let mut age: usize = 0; + for val in vals { + if idx > 2 { + return Default::default(); + } + if idx == 0 { + name = val; + } else if idx == 1 { + if let Ok(age_num) = val.parse::() { + age = age_num; + } else { + return Default::default(); + } + } + idx += 1; + } + if idx != 2 || name.is_empty() { + return Default::default(); + } + return Person { name: String::from(name), age }; } } @@ -54,6 +78,7 @@ fn main() { #[cfg(test)] mod tests { use super::*; + #[test] fn test_default() { // Test that the default person is 30 year old John @@ -61,6 +86,7 @@ mod tests { assert_eq!(dp.name, "John"); assert_eq!(dp.age, 30); } + #[test] fn test_bad_convert() { // Test that John is returned when bad string is provided @@ -68,6 +94,7 @@ mod tests { assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } + #[test] fn test_good_convert() { // Test that "Mark,20" works @@ -75,6 +102,7 @@ mod tests { assert_eq!(p.name, "Mark"); assert_eq!(p.age, 20); } + #[test] fn test_bad_age() { // Test that "Mark,twenty" will return the default person due to an error in parsing age diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index fe168159..fc759bbb 100644 --- a/exercises/conversions/from_str.rs +++ b/exercises/conversions/from_str.rs @@ -28,8 +28,6 @@ enum ParsePersonError { ParseInt(ParseIntError), } -// I AM NOT DONE - // Steps: // 1. If the length of the provided string is 0, an error should be returned // 2. Split the given string on the commas present in it @@ -46,6 +44,36 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s.is_empty() { + return Err(ParsePersonError::Empty); + } + let vals = s.split(","); + let mut idx = 0; + let mut name: &str = ""; + let mut age: usize = 0; + for val in vals { + if idx > 2 { + return Err(ParsePersonError::BadLen); + } + if idx == 0 { + name = val; + } else if idx == 1 { + match val.parse::() { + Ok(age_num) => { age = age_num } + Err(err) => { + return Err(ParsePersonError::ParseInt(err)); + } + } + } + idx += 1; + } + if idx != 2 { + return Err(ParsePersonError::BadLen); + } + if name.is_empty() { + return Err(ParsePersonError::NoName); + } + return Ok(Person { name: String::from(name), age }); } } @@ -62,6 +90,7 @@ mod tests { fn empty_input() { assert_eq!("".parse::(), Err(ParsePersonError::Empty)); } + #[test] fn good_input() { let p = "John,32".parse::(); @@ -70,6 +99,7 @@ mod tests { assert_eq!(p.name, "John"); assert_eq!(p.age, 32); } + #[test] fn missing_age() { assert!(matches!( diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index fa98bc90..3f1c61c4 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -7,6 +7,9 @@ use std::convert::{TryFrom, TryInto}; +const LEFT_MARGIN: i16 = 0; +const RIGHT_MARGIN: i16 = 255; + #[derive(Debug, PartialEq)] struct Color { red: u8, @@ -23,8 +26,6 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE - // Your task is to complete this implementation // and return an Ok result of inner type Color. // You need to create an implementation for a tuple of three integers, @@ -38,6 +39,12 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + if tuple.0 < LEFT_MARGIN || tuple.0 > RIGHT_MARGIN || + tuple.1 < LEFT_MARGIN || tuple.1 > RIGHT_MARGIN || + tuple.2 < LEFT_MARGIN || tuple.2 > RIGHT_MARGIN { + return Err(IntoColorError::IntConversion); + } + return Ok(Color { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 }); } } @@ -45,6 +52,27 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + let mut red: u8 = 0; + let mut green: u8 = 0; + let mut blue: u8 = 0; + for (idx, num) in arr.iter().enumerate() { + if idx > 2 { + return Err(IntoColorError::BadLen); + } + if num < &LEFT_MARGIN || num > &RIGHT_MARGIN { + return Err(IntoColorError::IntConversion); + } + if idx == 0 { + red = *num as u8; + } + if idx == 1 { + green = *num as u8; + } + if idx == 2 { + blue = *num as u8; + } + } + return Ok(Color { red, green, blue }); } } @@ -52,6 +80,30 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len() != 3 { + return Err(IntoColorError::BadLen); + } + let mut red: u8 = 0; + let mut green: u8 = 0; + let mut blue: u8 = 0; + for (idx, num) in slice.iter().enumerate() { + if idx > 2 { + return Err(IntoColorError::BadLen); + } + if num < &LEFT_MARGIN || num > &RIGHT_MARGIN { + return Err(IntoColorError::IntConversion); + } + if idx == 0 { + red = *num as u8; + } + if idx == 1 { + green = *num as u8; + } + if idx == 2 { + blue = *num as u8; + } + } + return Ok(Color { red, green, blue }); } } @@ -84,6 +136,7 @@ mod tests { Err(IntoColorError::IntConversion) ); } + #[test] fn test_tuple_out_of_range_negative() { assert_eq!( @@ -91,6 +144,7 @@ mod tests { Err(IntoColorError::IntConversion) ); } + #[test] fn test_tuple_sum() { assert_eq!( @@ -98,6 +152,7 @@ mod tests { Err(IntoColorError::IntConversion) ); } + #[test] fn test_tuple_correct() { let c: Result = (183, 65, 14).try_into(); @@ -107,25 +162,29 @@ mod tests { Color { red: 183, green: 65, - blue: 14 + blue: 14, } ); } + #[test] fn test_array_out_of_range_positive() { let c: Result = [1000, 10000, 256].try_into(); assert_eq!(c, Err(IntoColorError::IntConversion)); } + #[test] fn test_array_out_of_range_negative() { let c: Result = [-10, -256, -1].try_into(); assert_eq!(c, Err(IntoColorError::IntConversion)); } + #[test] fn test_array_sum() { let c: Result = [-1, 255, 255].try_into(); assert_eq!(c, Err(IntoColorError::IntConversion)); } + #[test] fn test_array_correct() { let c: Result = [183, 65, 14].try_into(); @@ -135,10 +194,11 @@ mod tests { Color { red: 183, green: 65, - blue: 14 + blue: 14, } ); } + #[test] fn test_slice_out_of_range_positive() { let arr = [10000, 256, 1000]; @@ -147,6 +207,7 @@ mod tests { Err(IntoColorError::IntConversion) ); } + #[test] fn test_slice_out_of_range_negative() { let arr = [-256, -1, -10]; @@ -155,6 +216,7 @@ mod tests { Err(IntoColorError::IntConversion) ); } + #[test] fn test_slice_sum() { let arr = [-1, 255, 255]; @@ -163,6 +225,7 @@ mod tests { Err(IntoColorError::IntConversion) ); } + #[test] fn test_slice_correct() { let v = vec![183, 65, 14]; @@ -173,15 +236,17 @@ mod tests { Color { red: 183, green: 65, - blue: 14 + blue: 14, } ); } + #[test] fn test_slice_excess_length() { let v = vec![0, 0, 0, 0]; assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); } + #[test] fn test_slice_insufficient_length() { let v = vec![0, 0]; diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 8c9b7113..0860d7e4 100644 --- a/exercises/conversions/using_as.rs +++ b/exercises/conversions/using_as.rs @@ -6,11 +6,9 @@ // and returns the proper type. // Execute `rustlings hint using_as` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn average(values: &[f64]) -> f64 { let total = values.iter().sum::(); - total / values.len() + total / (values.len() as f64) } fn main() { diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs index 511ba740..2546f0a0 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -1,11 +1,12 @@ // enums1.rs -// No hints this time! ;) - -// I AM NOT DONE +// No hints this time! :) #[derive(Debug)] enum Message { - // TODO: define a few types of messages as used below + Quit, + Echo, + Move, + ChangeColor, } fn main() { diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs index 167a6b2e..149e1e25 100644 --- a/exercises/enums/enums2.rs +++ b/exercises/enums/enums2.rs @@ -1,11 +1,12 @@ // enums2.rs // Execute `rustlings hint enums2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(Debug)] enum Message { - // TODO: define the different variants used below + Move { x: usize, y: usize }, + Echo(String), + ChangeColor(u8, u8, u8), + Quit, } impl Message { diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs index a2a9d586..15fefc5c 100644 --- a/exercises/enums/enums3.rs +++ b/exercises/enums/enums3.rs @@ -2,10 +2,11 @@ // Address all the TODOs to make the tests pass! // Execute `rustlings hint enums3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - enum Message { - // TODO: implement the message variant types based on their usage below + ChangeColor(u8, u8, u8), + Echo(String), + Move(Point), + Quit, } struct Point { @@ -37,8 +38,18 @@ impl State { } fn process(&mut self, message: Message) { - // TODO: create a match expression to process the different message variants - // Remember: When passing a tuple as a function argument, you'll need extra parentheses: fn function((t, u, p, l, e)) + match message { + Message::ChangeColor(r, g, b) => { + self.change_color((r, g, b)) + } + Message::Move(point) => { + self.move_position(point) + } + Message::Echo(s) => { + self.echo(s) + } + Message::Quit => { self.quit() } + } } } diff --git a/exercises/functions/functions1.rs b/exercises/functions/functions1.rs index 03d8af70..bd0ce077 100644 --- a/exercises/functions/functions1.rs +++ b/exercises/functions/functions1.rs @@ -1,8 +1,8 @@ // functions1.rs // Execute `rustlings hint functions1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { call_me(); } + +fn call_me() {} \ No newline at end of file diff --git a/exercises/functions/functions2.rs b/exercises/functions/functions2.rs index 7d40a578..5a51bdfb 100644 --- a/exercises/functions/functions2.rs +++ b/exercises/functions/functions2.rs @@ -1,13 +1,11 @@ // functions2.rs // Execute `rustlings hint functions2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { call_me(3); } -fn call_me(num:) { +fn call_me(num: i32) { for i in 0..num { println!("Ring! Call number {}", i + 1); } diff --git a/exercises/functions/functions3.rs b/exercises/functions/functions3.rs index 3b9e585b..617a050a 100644 --- a/exercises/functions/functions3.rs +++ b/exercises/functions/functions3.rs @@ -1,10 +1,8 @@ // functions3.rs // Execute `rustlings hint functions3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - call_me(); + call_me(10); } fn call_me(num: u32) { diff --git a/exercises/functions/functions4.rs b/exercises/functions/functions4.rs index 65d5be4f..40677fc9 100644 --- a/exercises/functions/functions4.rs +++ b/exercises/functions/functions4.rs @@ -7,14 +7,12 @@ // in the signatures for now. If anything, this is a good way to peek ahead // to future exercises!) -// I AM NOT DONE - fn main() { let original_price = 51; println!("Your sale price is {}", sale_price(original_price)); } -fn sale_price(price: i32) -> { +fn sale_price(price: i32) -> i32 { if is_even(price) { price - 10 } else { diff --git a/exercises/functions/functions5.rs b/exercises/functions/functions5.rs index 5d762961..ee8210ab 100644 --- a/exercises/functions/functions5.rs +++ b/exercises/functions/functions5.rs @@ -1,13 +1,11 @@ // functions5.rs // Execute `rustlings hint functions5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { let answer = square(3); println!("The square of 3 is {}", answer); } fn square(num: i32) -> i32 { - num * num; + num * num } diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs index fd8dd2f8..17176241 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -10,17 +10,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("pear"), 5); basket } diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index a4f069a8..aa42d8b5 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -13,8 +13,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)] @@ -36,9 +34,10 @@ 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.contains_key(&fruit) { + continue; + } + basket.insert(fruit, 10); } } diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index ad3baa68..840ea72c 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 team name and its goal details. @@ -35,11 +33,20 @@ 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 scores.contains_key(team_1_name.as_str()) { + let mut team1 = scores.get_mut(team_1_name.as_str()).unwrap(); + team1.goals_scored += team_1_score; + team1.goals_conceded += team_2_score; + } else { + scores.insert(team_1_name.clone(), Team { name: team_1_name.clone(), goals_scored: team_1_score, goals_conceded: team_2_score }); + } + if scores.contains_key(team_2_name.as_str()) { + let mut team2 = scores.get_mut(team_2_name.as_str()).unwrap(); + team2.goals_scored += team_2_score; + team2.goals_conceded += team_1_score; + } else { + scores.insert(team_2_name.clone(), Team { name: team_2_name.clone(), goals_scored: team_2_score, goals_conceded: team_1_score }); + } } scores } diff --git a/exercises/if/if1.rs b/exercises/if/if1.rs index 587e03f8..7785be43 100644 --- a/exercises/if/if1.rs +++ b/exercises/if/if1.rs @@ -1,13 +1,16 @@ // if1.rs // Execute `rustlings hint if1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub fn bigger(a: i32, b: i32) -> i32 { // Complete this function to return the bigger number! // Do not use: // - another function call // - additional variables + return if a > b { + a + } else { + b + }; } // Don't mind this for now :) diff --git a/exercises/if/if2.rs b/exercises/if/if2.rs index effddbb6..129a4a25 100644 --- a/exercises/if/if2.rs +++ b/exercises/if/if2.rs @@ -4,13 +4,13 @@ // Step 2: Get the bar_for_fuzz and default_to_baz tests passing! // Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub fn foo_if_fizz(fizzish: &str) -> &str { if fizzish == "fizz" { "foo" + } else if fizzish == "fuzz" { + "bar" } else { - 1 + "baz" } } diff --git a/exercises/intro/intro1.rs b/exercises/intro/intro1.rs index cfc55c30..54889778 100644 --- a/exercises/intro/intro1.rs +++ b/exercises/intro/intro1.rs @@ -9,8 +9,6 @@ // when you change one of the lines below! Try adding a `println!` line, or try changing // what it outputs in your terminal. Try removing a semicolon and see what happens! -// I AM NOT DONE - fn main() { println!("Hello and"); println!(r#" welcome to... "#); diff --git a/exercises/intro/intro2.rs b/exercises/intro/intro2.rs index efc1af20..b5b1d0a8 100644 --- a/exercises/intro/intro2.rs +++ b/exercises/intro/intro2.rs @@ -2,8 +2,6 @@ // Make the code print a greeting to the world. // Execute `rustlings hint intro2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - println!("Hello {}!"); + println!("Hello {}!", "World"); } diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs index 8dd0e402..09d5ab3e 100644 --- a/exercises/modules/modules1.rs +++ b/exercises/modules/modules1.rs @@ -1,15 +1,13 @@ // modules1.rs // 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 c30a3897..33848947 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -3,12 +3,9 @@ // 'use' and 'as' keywords. Fix these 'use' statements to make the code compile. // 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 35e07990..f669ecf9 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -5,10 +5,7 @@ // from the std::time module. Bonus style points if you can do it with one line! // 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::{SystemTime, UNIX_EPOCH}; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/move_semantics/move_semantics1.rs b/exercises/move_semantics/move_semantics1.rs index aac6dfc3..c60ee74f 100644 --- a/exercises/move_semantics/move_semantics1.rs +++ b/exercises/move_semantics/move_semantics1.rs @@ -1,12 +1,10 @@ // move_semantics1.rs // Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { let vec0 = Vec::new(); - let vec1 = fill_vec(vec0); + let mut vec1 = fill_vec(vec0); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); diff --git a/exercises/move_semantics/move_semantics2.rs b/exercises/move_semantics/move_semantics2.rs index 93bb82ef..26dd2325 100644 --- a/exercises/move_semantics/move_semantics2.rs +++ b/exercises/move_semantics/move_semantics2.rs @@ -5,28 +5,23 @@ // vec0 has length 3 content `[22, 44, 66]` // vec1 has length 4 content `[22, 44, 66, 88]` -// I AM NOT DONE - fn main() { - let vec0 = Vec::new(); + let mut vec0 = Vec::new(); // Do not move the following line! - let mut vec1 = fill_vec(vec0); + fill_vec(&mut vec0); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); + let mut vec1 = vec0.clone(); vec1.push(88); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); } -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - +fn fill_vec(vec: &mut Vec) { vec.push(22); vec.push(44); vec.push(66); - - vec } diff --git a/exercises/move_semantics/move_semantics3.rs b/exercises/move_semantics/move_semantics3.rs index eaa30e33..7bbabcdc 100644 --- a/exercises/move_semantics/move_semantics3.rs +++ b/exercises/move_semantics/move_semantics3.rs @@ -3,12 +3,10 @@ // (no lines with multiple semicolons necessary!) // Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let vec0 = Vec::new(); + let mut vec0 = Vec::new(); - let mut vec1 = fill_vec(vec0); + let mut vec1 = fill_vec(&mut vec0); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); @@ -17,10 +15,10 @@ fn main() { println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); } -fn fill_vec(vec: Vec) -> Vec { +fn fill_vec(vec: &mut Vec) -> Vec { vec.push(22); vec.push(44); vec.push(66); - vec + vec.clone() } diff --git a/exercises/move_semantics/move_semantics4.rs b/exercises/move_semantics/move_semantics4.rs index 99834ec3..21077612 100644 --- a/exercises/move_semantics/move_semantics4.rs +++ b/exercises/move_semantics/move_semantics4.rs @@ -4,12 +4,8 @@ // function. // Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let vec0 = Vec::new(); - - let mut vec1 = fill_vec(vec0); + let mut vec1 = fill_vec(); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); @@ -20,7 +16,7 @@ fn main() { // `fill_vec()` no longer takes `vec: Vec` as argument fn fill_vec() -> Vec { - let mut vec = vec; + let mut vec = Vec::new(); vec.push(22); vec.push(44); diff --git a/exercises/move_semantics/move_semantics5.rs b/exercises/move_semantics/move_semantics5.rs index 36eae127..c475bfd9 100644 --- a/exercises/move_semantics/move_semantics5.rs +++ b/exercises/move_semantics/move_semantics5.rs @@ -3,13 +3,15 @@ // adding, changing or removing any of them. // Execute `rustlings hint move_semantics5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { let mut x = 100; - let y = &mut x; - let z = &mut x; - *y += 100; - *z += 1000; + { + let y = &mut x; + *y += 100; + } + { + let z = &mut x; + *z += 1000; + } assert_eq!(x, 1200); } diff --git a/exercises/move_semantics/move_semantics6.rs b/exercises/move_semantics/move_semantics6.rs index eb52a848..055ea5bf 100644 --- a/exercises/move_semantics/move_semantics6.rs +++ b/exercises/move_semantics/move_semantics6.rs @@ -2,24 +2,22 @@ // Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand for a hint. // You can't change anything except adding or removing references. -// I AM NOT DONE - fn main() { let data = "Rust is great!".to_string(); - get_char(data); + get_char(&data); - string_uppercase(&data); + string_uppercase(data); } // Should not take ownership -fn get_char(data: String) -> char { +fn get_char(data: &String) -> char { data.chars().last().unwrap() } // Should take ownership -fn string_uppercase(mut data: &String) { - data = &data.to_uppercase(); +fn string_uppercase(mut data: String) { + data = data.to_uppercase(); println!("{}", data); } diff --git a/exercises/primitive_types/primitive_types1.rs b/exercises/primitive_types/primitive_types1.rs index 09121392..91734c69 100644 --- a/exercises/primitive_types/primitive_types1.rs +++ b/exercises/primitive_types/primitive_types1.rs @@ -2,8 +2,6 @@ // Fill in the rest of the line that has code missing! // No hints, there's no tricks, just get used to typing these :) -// I AM NOT DONE - fn main() { // Booleans (`bool`) @@ -12,7 +10,7 @@ fn main() { println!("Good morning!"); } - let // Finish the rest of this line like the example! Or make it be false! + let is_evening = false; // Finish the rest of this line like the example! Or make it be false! if is_evening { println!("Good evening!"); } diff --git a/exercises/primitive_types/primitive_types2.rs b/exercises/primitive_types/primitive_types2.rs index 8730baab..195c40f1 100644 --- a/exercises/primitive_types/primitive_types2.rs +++ b/exercises/primitive_types/primitive_types2.rs @@ -2,8 +2,6 @@ // Fill in the rest of the line that has code missing! // No hints, there's no tricks, just get used to typing these :) -// I AM NOT DONE - fn main() { // Characters (`char`) @@ -18,7 +16,7 @@ fn main() { println!("Neither alphabetic nor numeric!"); } - let // Finish this line like the example! What's your favorite character? + let your_character = 'B'; // Finish this line like the example! What's your favorite character? // Try a letter, try a number, try a special character, try a character // from a different language than your own, try an emoji! if your_character.is_alphabetic() { diff --git a/exercises/primitive_types/primitive_types3.rs b/exercises/primitive_types/primitive_types3.rs index fa7d019a..f645baf1 100644 --- a/exercises/primitive_types/primitive_types3.rs +++ b/exercises/primitive_types/primitive_types3.rs @@ -2,10 +2,8 @@ // Create an array with at least 100 elements in it where the ??? is. // Execute `rustlings hint primitive_types3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let a = ??? + let a: &[i32; 5] = &[1, 2, 3, 4, 5]; if a.len() >= 100 { println!("Wow, that's a big array!"); diff --git a/exercises/primitive_types/primitive_types4.rs b/exercises/primitive_types/primitive_types4.rs index 71fa243c..e3371784 100644 --- a/exercises/primitive_types/primitive_types4.rs +++ b/exercises/primitive_types/primitive_types4.rs @@ -2,13 +2,11 @@ // Get a slice out of Array a where the ??? is so that the test passes. // Execute `rustlings hint primitive_types4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[test] fn slice_out_of_array() { let a = [1, 2, 3, 4, 5]; - let nice_slice = ??? + let nice_slice = &a[1..4]; assert_eq!([2, 3, 4], nice_slice) } diff --git a/exercises/primitive_types/primitive_types5.rs b/exercises/primitive_types/primitive_types5.rs index 4fd9141f..5cba3c15 100644 --- a/exercises/primitive_types/primitive_types5.rs +++ b/exercises/primitive_types/primitive_types5.rs @@ -2,11 +2,9 @@ // Destructure the `cat` tuple so that the println will work. // Execute `rustlings hint primitive_types5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { let cat = ("Furry McFurson", 3.5); - let /* your pattern here */ = cat; + let (name, age) = cat; println!("{} is {} years old.", name, age); } diff --git a/exercises/primitive_types/primitive_types6.rs b/exercises/primitive_types/primitive_types6.rs index ddf8b423..bd92c2e9 100644 --- a/exercises/primitive_types/primitive_types6.rs +++ b/exercises/primitive_types/primitive_types6.rs @@ -3,14 +3,12 @@ // You can put the expression for the second element where ??? is so that the test passes. // Execute `rustlings hint primitive_types6` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[test] fn indexing_tuple() { let numbers = (1, 2, 3); // Replace below ??? with the tuple indexing syntax. - let second = ???; + let second = numbers.1; assert_eq!(2, second, - "This is not the 2nd number in the tuple!") + "This is not the 2nd number in the tuple!") } diff --git a/exercises/quiz1.rs b/exercises/quiz1.rs index dbb5cdc9..cf481115 100644 --- a/exercises/quiz1.rs +++ b/exercises/quiz1.rs @@ -10,10 +10,14 @@ // Write a function that calculates the price of an order of apples given // the quantity bought. No hints this time! -// I AM NOT DONE - // Put your function here! -// fn calculate_price_of_apples { +fn calculate_price_of_apples(num: i32) -> i32 { + return if num <= 40 { + num * 2 + } else { + num + }; +} // Don't modify this function! #[test] diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index 5c42dae0..ee56f4fb 100644 --- a/exercises/quiz2.rs +++ b/exercises/quiz2.rs @@ -18,8 +18,6 @@ // - The output element is going to be a Vector of strings. // No hints this time! -// I AM NOT DONE - pub enum Command { Uppercase, Trim, @@ -29,12 +27,24 @@ 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![]; - for (string, command) in input.iter() { - // TODO: Complete the function body. You can do it! + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut output: Vec = vec![]; + for (s, cmd) in input.iter() { + let mut string = s.clone(); + match cmd { + Command::Uppercase => { + string = string.to_uppercase(); + } + Command::Trim => { + string = string.trim().to_string(); + } + Command::Append(us) => { + for i in 0..(*us as i32) { + string.push_str("bar"); + } + } + } + output.push(string); } output } @@ -42,8 +52,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 0de86a1d..fd74ea38 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` 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" + "blue".to_string() } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 0c48ec95..87a20c78 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` 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.as_str()) { 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 e2353aec..097255fe 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -1,21 +1,18 @@ // strings3.rs // 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! - ??? + input.trim().to_string() } fn compose_me(input: &str) -> String { - // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? + let mut owned_str = String::from(input.clone()); + owned_str.push_str(" world!"); + owned_str } fn replace_me(input: &str) -> String { - // TODO: Replace "cars" in the string with "balloons"! - ??? + input.replace("car", "balloon").to_string() } #[cfg(test)] diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs index c410b562..aa9fee70 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -6,24 +6,24 @@ // before the parentheses on each line. If you're right, it will compile! // No hints this time! -// I AM NOT DONE - fn string_slice(arg: &str) { println!("{}", arg); } + fn string(arg: String) { println!("{}", arg); } 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_slice("nice weather".into()); + 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/structs/structs1.rs b/exercises/structs/structs1.rs index 0d91c469..c3dd026f 100644 --- a/exercises/structs/structs1.rs +++ b/exercises/structs/structs1.rs @@ -2,13 +2,13 @@ // Address all the TODOs to make the tests pass! // Execute `rustlings hint structs1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - struct ColorClassicStruct { - // TODO: Something goes here + red: u8, + green: u8, + blue: u8, } -struct ColorTupleStruct(/* TODO: Something goes here */); +struct ColorTupleStruct(u8, u8, u8); #[derive(Debug)] struct UnitLikeStruct; @@ -19,8 +19,7 @@ mod tests { #[test] fn classic_c_structs() { - // TODO: Instantiate a classic c struct! - // let green = + let green = ColorClassicStruct { red: 0, green: 255, blue: 0 }; assert_eq!(green.red, 0); assert_eq!(green.green, 255); @@ -29,8 +28,7 @@ mod tests { #[test] fn tuple_structs() { - // TODO: Instantiate a tuple struct! - // let green = + let green = ColorTupleStruct(0, 255, 0); assert_eq!(green.0, 0); assert_eq!(green.1, 255); @@ -39,8 +37,7 @@ mod tests { #[test] fn unit_structs() { - // TODO: Instantiate a unit-like struct! - // let unit_like_struct = + let unit_like_struct = UnitLikeStruct; let message = format!("{:?}s are fun!", unit_like_struct); assert_eq!(message, "UnitLikeStructs are fun!"); diff --git a/exercises/structs/structs2.rs b/exercises/structs/structs2.rs index 32e311fa..612080f3 100644 --- a/exercises/structs/structs2.rs +++ b/exercises/structs/structs2.rs @@ -2,8 +2,6 @@ // Address all the TODOs to make the tests pass! // Execute `rustlings hint structs2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(Debug)] struct Order { name: String, @@ -34,8 +32,15 @@ mod tests { #[test] fn your_order() { let order_template = create_order_template(); - // TODO: Create your own order using the update syntax and template above! - // let your_order = + let your_order = Order { + name: String::from("Hacker in Rust"), + year: order_template.year, + made_by_phone: order_template.made_by_phone, + made_by_mobile: order_template.made_by_mobile, + made_by_email: order_template.made_by_email, + item_number: order_template.item_number, + count: 1, + }; assert_eq!(your_order.name, "Hacker in Rust"); assert_eq!(your_order.year, order_template.year); assert_eq!(your_order.made_by_phone, order_template.made_by_phone); diff --git a/exercises/structs/structs3.rs b/exercises/structs/structs3.rs index 3536a457..4f07f011 100644 --- a/exercises/structs/structs3.rs +++ b/exercises/structs/structs3.rs @@ -4,8 +4,6 @@ // Make the code compile and the tests pass! // Execute `rustlings hint structs3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(Debug)] struct Package { sender_country: String, @@ -26,12 +24,12 @@ impl Package { } } - fn is_international(&self) -> ??? { - // Something goes here... + fn is_international(&self) -> bool { + self.sender_country != self.recipient_country } - fn get_fees(&self, cents_per_gram: i32) -> ??? { - // Something goes here... + fn get_fees(&self, cents_per_gram: i32) -> i32 { + return if cents_per_gram < 0 { 0 } else { self.weight_in_grams * cents_per_gram }; } } diff --git a/exercises/variables/variables1.rs b/exercises/variables/variables1.rs index f4d182ac..84de9fdc 100644 --- a/exercises/variables/variables1.rs +++ b/exercises/variables/variables1.rs @@ -2,9 +2,7 @@ // Make me compile! // Execute `rustlings hint variables1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - x = 5; + let x = 5; println!("x has the value {}", x); } diff --git a/exercises/variables/variables2.rs b/exercises/variables/variables2.rs index 641aeb8e..de4bd796 100644 --- a/exercises/variables/variables2.rs +++ b/exercises/variables/variables2.rs @@ -1,10 +1,8 @@ // variables2.rs // Execute `rustlings hint variables2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let x; + let x = 5; if x == 10 { println!("x is ten!"); } else { diff --git a/exercises/variables/variables3.rs b/exercises/variables/variables3.rs index 819b1bc7..619895fc 100644 --- a/exercises/variables/variables3.rs +++ b/exercises/variables/variables3.rs @@ -1,9 +1,7 @@ // variables3.rs // Execute `rustlings hint variables3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let x: i32; + let x: i32 = 10; println!("Number {}", x); } diff --git a/exercises/variables/variables4.rs b/exercises/variables/variables4.rs index 54491b0a..eeadf1d1 100644 --- a/exercises/variables/variables4.rs +++ b/exercises/variables/variables4.rs @@ -1,10 +1,8 @@ // variables4.rs // Execute `rustlings hint variables4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let x = 3; + let mut x = 3; println!("Number {}", x); x = 5; // don't change this line println!("Number {}", x); diff --git a/exercises/variables/variables5.rs b/exercises/variables/variables5.rs index 0e670d2a..1b9d9f48 100644 --- a/exercises/variables/variables5.rs +++ b/exercises/variables/variables5.rs @@ -1,11 +1,9 @@ // variables5.rs // Execute `rustlings hint variables5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { let number = "T-H-R-E-E"; // don't change this line println!("Spell a Number : {}", number); - number = 3; // don't rename this variable + let number = 3; // don't rename this variable println!("Number plus two is : {}", number + 2); } diff --git a/exercises/variables/variables6.rs b/exercises/variables/variables6.rs index a8520122..f7f2f108 100644 --- a/exercises/variables/variables6.rs +++ b/exercises/variables/variables6.rs @@ -1,9 +1,8 @@ // variables6.rs // Execute `rustlings hint variables6` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE +const NUMBER: i32 = 3; -const NUMBER = 3; fn main() { println!("Number {}", NUMBER); } diff --git a/exercises/vecs/vecs1.rs b/exercises/vecs/vecs1.rs index 4e8c4cbb..f537f198 100644 --- a/exercises/vecs/vecs1.rs +++ b/exercises/vecs/vecs1.rs @@ -4,11 +4,9 @@ // Make me compile and pass the test! // Execute `rustlings hint vecs1` or use the `hint` watch subcommand for a hint. -// 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 = vec![10, 20, 30, 40]; (a, v) } diff --git a/exercises/vecs/vecs2.rs b/exercises/vecs/vecs2.rs index 1ea26071..c09a7d6a 100644 --- a/exercises/vecs/vecs2.rs +++ b/exercises/vecs/vecs2.rs @@ -6,25 +6,16 @@ // // Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn vec_loop(mut v: Vec) -> Vec { for element in v.iter_mut() { - // TODO: Fill this up so that each element in the Vec `v` is - // multiplied by 2. - ??? + *element = *element * 2; } - // At this point, `v` should be equal to [4, 8, 12, 16, 20]. v } fn vec_map(v: &Vec) -> Vec { - v.iter().map(|element| { - // TODO: Do the same thing as above - but instead of mutating the - // Vec, you can just return the new number! - ??? - }).collect() + v.iter().map(|element| { element * 2 }).collect() } #[cfg(test)]