diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..4f4d69a82e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "mirrord.promptUsingBinary": false, + "makefile.configureOnOpen": false +} \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..6ebba2edfe --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +format: + cargo fmt --all --verbose --check \ No newline at end of file diff --git a/exercises/00_intro/intro2.rs b/exercises/00_intro/intro2.rs index c6cb6451ae..03e376ed35 100644 --- a/exercises/00_intro/intro2.rs +++ b/exercises/00_intro/intro2.rs @@ -1,4 +1,4 @@ fn main() { // TODO: Fix the code to print "Hello world!". - printline!("Hello world!"); + println!("Hello world!"); } diff --git a/exercises/01_variables/variables1.rs b/exercises/01_variables/variables1.rs index f83b44d415..ec1bcacb53 100644 --- a/exercises/01_variables/variables1.rs +++ b/exercises/01_variables/variables1.rs @@ -1,6 +1,6 @@ fn main() { // TODO: Add the missing keyword. - x = 5; + let x = 5; println!("x has the value {x}"); } diff --git a/exercises/01_variables/variables2.rs b/exercises/01_variables/variables2.rs index e2a360351a..e2fd5d03f2 100644 --- a/exercises/01_variables/variables2.rs +++ b/exercises/01_variables/variables2.rs @@ -1,6 +1,6 @@ fn main() { // TODO: Change the line below to fix the compiler error. - let x; + let x = 10; if x == 10 { println!("x is ten!"); diff --git a/exercises/01_variables/variables3.rs b/exercises/01_variables/variables3.rs index 06f35bb1e2..0ed3b38bb8 100644 --- a/exercises/01_variables/variables3.rs +++ b/exercises/01_variables/variables3.rs @@ -1,6 +1,6 @@ fn main() { // TODO: Change the line below to fix the compiler error. - let x: i32; + let x: i32 = 0; println!("Number {x}"); } diff --git a/exercises/01_variables/variables4.rs b/exercises/01_variables/variables4.rs index 6c138b18b9..90d4ef05d1 100644 --- a/exercises/01_variables/variables4.rs +++ b/exercises/01_variables/variables4.rs @@ -1,6 +1,6 @@ // TODO: Fix the compiler error. fn main() { - let x = 3; + let mut x = 3; println!("Number {x}"); x = 5; // Don't change this line diff --git a/exercises/01_variables/variables5.rs b/exercises/01_variables/variables5.rs index cf5620da5f..085e0994f7 100644 --- a/exercises/01_variables/variables5.rs +++ b/exercises/01_variables/variables5.rs @@ -3,6 +3,6 @@ fn main() { println!("Spell a number: {number}"); // TODO: Fix the compiler error by changing the line below without renaming the variable. - number = 3; + let number = 3; println!("Number plus two is: {}", number + 2); } diff --git a/exercises/01_variables/variables6.rs b/exercises/01_variables/variables6.rs index 4a040fddac..9c78e35c34 100644 --- a/exercises/01_variables/variables6.rs +++ b/exercises/01_variables/variables6.rs @@ -1,5 +1,5 @@ // TODO: Change the line below to fix the compiler error. -const NUMBER = 3; +const NUMBER: i8 = 3; fn main() { println!("Number: {NUMBER}"); diff --git a/exercises/02_functions/functions1.rs b/exercises/02_functions/functions1.rs index a812c21bf2..e079808535 100644 --- a/exercises/02_functions/functions1.rs +++ b/exercises/02_functions/functions1.rs @@ -1,5 +1,8 @@ // TODO: Add some function with the name `call_me` without arguments or a return value. + +fn call_me() {} + fn main() { call_me(); // Don't change this line } diff --git a/exercises/02_functions/functions2.rs b/exercises/02_functions/functions2.rs index 2c773c6b7f..a2cffc1a7b 100644 --- a/exercises/02_functions/functions2.rs +++ b/exercises/02_functions/functions2.rs @@ -1,5 +1,5 @@ // TODO: Add the missing type of the argument `num` after the colon `:`. -fn call_me(num:) { +fn call_me(num: i32) { for i in 0..num { println!("Ring! Call number {}", i + 1); } diff --git a/exercises/02_functions/functions3.rs b/exercises/02_functions/functions3.rs index 8d65477219..a226e66628 100644 --- a/exercises/02_functions/functions3.rs +++ b/exercises/02_functions/functions3.rs @@ -6,5 +6,5 @@ fn call_me(num: u8) { fn main() { // TODO: Fix the function call. - call_me(); + call_me(1); } diff --git a/exercises/02_functions/functions4.rs b/exercises/02_functions/functions4.rs index b22bffdaf2..60ab17d4f8 100644 --- a/exercises/02_functions/functions4.rs +++ b/exercises/02_functions/functions4.rs @@ -8,7 +8,7 @@ fn is_even(num: i64) -> bool { } // TODO: Fix the function signature. -fn sale_price(price: i64) -> { +fn sale_price(price: i64) -> i64{ if is_even(price) { price - 10 } else { diff --git a/exercises/02_functions/functions5.rs b/exercises/02_functions/functions5.rs index 34a2ac7dce..a063100408 100644 --- a/exercises/02_functions/functions5.rs +++ b/exercises/02_functions/functions5.rs @@ -1,6 +1,6 @@ // TODO: Fix the function body without changing the signature. fn square(num: i32) -> i32 { - num * num; + num * num } fn main() { diff --git a/exercises/03_if/if1.rs b/exercises/03_if/if1.rs index e5a3c5a5b2..0f9c744bac 100644 --- a/exercises/03_if/if1.rs +++ b/exercises/03_if/if1.rs @@ -1,9 +1,10 @@ fn bigger(a: i32, b: i32) -> i32 { // TODO: Complete this function to return the bigger number! // If both numbers are equal, any of them can be returned. - // Do not use: - // - another function call - // - additional variables + if a > b { + return a + } + b } fn main() { diff --git a/exercises/03_if/if2.rs b/exercises/03_if/if2.rs index ca8493cc81..67312ecab9 100644 --- a/exercises/03_if/if2.rs +++ b/exercises/03_if/if2.rs @@ -1,9 +1,12 @@ // TODO: Fix the compiler error on this function. fn picky_eater(food: &str) -> &str { if food == "strawberry" { - "Yummy!" + return "Yummy!" + } + if food == "potato" { + "I guess I can eat that." } else { - 1 + "No thanks!" } } diff --git a/exercises/03_if/if3.rs b/exercises/03_if/if3.rs index 89164eb218..6d7a7f40d3 100644 --- a/exercises/03_if/if3.rs +++ b/exercises/03_if/if3.rs @@ -3,11 +3,11 @@ fn animal_habitat(animal: &str) -> &str { let identifier = if animal == "crab" { 1 } else if animal == "gopher" { - 2.0 + 2 } else if animal == "snake" { 3 } else { - "Unknown" + 4 }; // Don't change the expression below! diff --git a/exercises/04_primitive_types/primitive_types1.rs b/exercises/04_primitive_types/primitive_types1.rs index 84923c7500..499b2a8319 100644 --- a/exercises/04_primitive_types/primitive_types1.rs +++ b/exercises/04_primitive_types/primitive_types1.rs @@ -8,7 +8,7 @@ fn main() { // TODO: Define a boolean variable with the name `is_evening` before the `if` statement below. // The value of the variable should be the negation (opposite) of `is_morning`. - // let … + let is_evening = !is_morning; if is_evening { println!("Good evening!"); } diff --git a/exercises/04_primitive_types/primitive_types2.rs b/exercises/04_primitive_types/primitive_types2.rs index 14018475dd..320abca3a0 100644 --- a/exercises/04_primitive_types/primitive_types2.rs +++ b/exercises/04_primitive_types/primitive_types2.rs @@ -16,7 +16,7 @@ fn main() { // below with your favorite character. // Try a letter, try a digit (in single quotes), try a special character, try a character // from a different language than your own, try an emoji 😉 - // let your_character = ''; + let your_character = 'X'; if your_character.is_alphabetic() { println!("Alphabetical!"); diff --git a/exercises/04_primitive_types/primitive_types3.rs b/exercises/04_primitive_types/primitive_types3.rs index 9b79c0cf2a..4abdbfeb03 100644 --- a/exercises/04_primitive_types/primitive_types3.rs +++ b/exercises/04_primitive_types/primitive_types3.rs @@ -1,6 +1,6 @@ fn main() { // TODO: Create an array called `a` with at least 100 elements in it. - // let a = ??? + let a = [0; 100]; if a.len() >= 100 { println!("Wow, that's a big array!"); diff --git a/exercises/04_primitive_types/primitive_types4.rs b/exercises/04_primitive_types/primitive_types4.rs index 16e4fd9321..a15feb1ca1 100644 --- a/exercises/04_primitive_types/primitive_types4.rs +++ b/exercises/04_primitive_types/primitive_types4.rs @@ -9,7 +9,7 @@ mod tests { let a = [1, 2, 3, 4, 5]; // TODO: Get a slice called `nice_slice` out of the array `a` so that the test passes. - // let nice_slice = ??? + let nice_slice = &a[1..4]; assert_eq!([2, 3, 4], nice_slice); } diff --git a/exercises/04_primitive_types/primitive_types5.rs b/exercises/04_primitive_types/primitive_types5.rs index 6e00ef51f8..1fdc335a0d 100644 --- a/exercises/04_primitive_types/primitive_types5.rs +++ b/exercises/04_primitive_types/primitive_types5.rs @@ -2,7 +2,7 @@ fn main() { let cat = ("Furry McFurson", 3.5); // TODO: Destructure the `cat` tuple in one statement so that the println works. - // let /* your pattern here */ = cat; + let (name, age) = cat; println!("{name} is {age} years old"); } diff --git a/exercises/04_primitive_types/primitive_types6.rs b/exercises/04_primitive_types/primitive_types6.rs index a97e53110e..e70cb69689 100644 --- a/exercises/04_primitive_types/primitive_types6.rs +++ b/exercises/04_primitive_types/primitive_types6.rs @@ -10,7 +10,7 @@ mod tests { // TODO: Use a tuple index to access the second element of `numbers` // and assign it to a variable called `second`. - // let second = ???; + let second = numbers.1; assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); } diff --git a/exercises/05_vecs/vecs1.rs b/exercises/05_vecs/vecs1.rs index a015c40f55..8d2fd41bd6 100644 --- a/exercises/05_vecs/vecs1.rs +++ b/exercises/05_vecs/vecs1.rs @@ -1,6 +1,7 @@ fn elems_to_vec(a: i32, b: i32, c: i32) -> Vec { // TODO: Return a vector containing the elements a, b and c (in this order). // Use the "vec!" macro. + vec![a,b,c] } fn main() { diff --git a/exercises/05_vecs/vecs2.rs b/exercises/05_vecs/vecs2.rs index 0c996266d8..2e4a55775e 100644 --- a/exercises/05_vecs/vecs2.rs +++ b/exercises/05_vecs/vecs2.rs @@ -4,6 +4,7 @@ fn vec_loop(input: &[i32]) -> Vec { for element in input { // TODO: Multiply each element in the `input` slice by 2 and push it to // the `output` vector. + output.push(element * 2); } output diff --git a/exercises/06_move_semantics/move_semantics1.rs b/exercises/06_move_semantics/move_semantics1.rs index 4eb3d618ef..bf55943249 100644 --- a/exercises/06_move_semantics/move_semantics1.rs +++ b/exercises/06_move_semantics/move_semantics1.rs @@ -1,6 +1,6 @@ // TODO: Fix the compiler error in this function. fn fill_vec(vec: Vec) -> Vec { - let vec = vec; + let mut vec = vec; vec.push(88); diff --git a/exercises/06_move_semantics/move_semantics2.rs b/exercises/06_move_semantics/move_semantics2.rs index a3ab7a0f18..e205b81357 100644 --- a/exercises/06_move_semantics/move_semantics2.rs +++ b/exercises/06_move_semantics/move_semantics2.rs @@ -20,7 +20,7 @@ mod tests { fn move_semantics2() { let vec0 = vec![22, 44, 66]; - let vec1 = fill_vec(vec0); + let vec1 = fill_vec(vec0.clone()); assert_eq!(vec0, [22, 44, 66]); assert_eq!(vec1, [22, 44, 66, 88]); diff --git a/exercises/06_move_semantics/move_semantics3.rs b/exercises/06_move_semantics/move_semantics3.rs index 11dbbbebff..4a90c2117c 100644 --- a/exercises/06_move_semantics/move_semantics3.rs +++ b/exercises/06_move_semantics/move_semantics3.rs @@ -1,5 +1,5 @@ // TODO: Fix the compiler error in the function without adding any new line. -fn fill_vec(vec: Vec) -> Vec { +fn fill_vec(mut vec: Vec) -> Vec { vec.push(88); vec diff --git a/exercises/06_move_semantics/move_semantics4.rs b/exercises/06_move_semantics/move_semantics4.rs index 56da988cd4..89b412f093 100644 --- a/exercises/06_move_semantics/move_semantics4.rs +++ b/exercises/06_move_semantics/move_semantics4.rs @@ -10,8 +10,8 @@ mod tests { fn move_semantics4() { let mut x = Vec::new(); let y = &mut x; - let z = &mut x; y.push(42); + let z = &mut x; z.push(13); assert_eq!(x, [42, 13]); } diff --git a/exercises/06_move_semantics/move_semantics5.rs b/exercises/06_move_semantics/move_semantics5.rs index cd0dafd08d..78d8c77e54 100644 --- a/exercises/06_move_semantics/move_semantics5.rs +++ b/exercises/06_move_semantics/move_semantics5.rs @@ -4,12 +4,12 @@ // removing references (the character `&`). // Shouldn't 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) { +fn string_uppercase(mut data: String) { data = data.to_uppercase(); println!("{data}"); @@ -18,7 +18,7 @@ fn string_uppercase(mut data: &String) { fn main() { let data = "Rust is great!".to_string(); - get_char(data); + get_char(&data); - string_uppercase(&data); + string_uppercase(data); } diff --git a/exercises/07_structs/structs1.rs b/exercises/07_structs/structs1.rs index 959c4c6a68..bdb10dbc1b 100644 --- a/exercises/07_structs/structs1.rs +++ b/exercises/07_structs/structs1.rs @@ -1,9 +1,12 @@ struct ColorRegularStruct { // TODO: Add the fields that the test `regular_structs` expects. // What types should the fields have? What are the minimum and maximum values for RGB colors? + red: u8, + green: u8, + blue: u8 } -struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */); +struct ColorTupleStruct(u8, u8, u8); #[derive(Debug)] struct UnitStruct; @@ -19,7 +22,7 @@ mod tests { #[test] fn regular_structs() { // TODO: Instantiate a regular struct. - // let green = + let green = ColorRegularStruct {red: 0, green: 255, blue: 0}; assert_eq!(green.red, 0); assert_eq!(green.green, 255); @@ -29,7 +32,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,7 +42,7 @@ mod tests { #[test] fn unit_structs() { // TODO: Instantiate a unit struct. - // let unit_struct = + let unit_struct = UnitStruct; let message = format!("{unit_struct:?}s are fun!"); assert_eq!(message, "UnitStructs are fun!"); diff --git a/exercises/07_structs/structs2.rs b/exercises/07_structs/structs2.rs index 79141af95d..04c77085f1 100644 --- a/exercises/07_structs/structs2.rs +++ b/exercises/07_structs/structs2.rs @@ -34,7 +34,15 @@ mod tests { 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: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 1, + }; assert_eq!(your_order.name, "Hacker in Rust"); assert_eq!(your_order.year, order_template.year); diff --git a/exercises/07_structs/structs3.rs b/exercises/07_structs/structs3.rs index d42729e13d..7fec65a638 100644 --- a/exercises/07_structs/structs3.rs +++ b/exercises/07_structs/structs3.rs @@ -10,21 +10,28 @@ struct Fireworks { rockets: usize, } -// TODO: Turn this function into an associated function on `Fireworks`. -fn new_fireworks() -> Fireworks { - Fireworks { rockets: 0 } -} +impl Fireworks { + fn new() -> Self { + Self::new_fireworks() + } -// TODO: Turn this function into a method on `Fireworks`. -fn add_rockets(fireworks: &mut Fireworks, rockets: usize) { - fireworks.rockets += rockets -} + // TODO: Turn this function into an associated function on `Fireworks`. + fn new_fireworks() -> Self { + Self { rockets: 0 } + } -// TODO: Turn this function into a method on `Fireworks`. -fn start(fireworks: Fireworks) -> String { - "🚀".repeat(fireworks.rockets) + // TODO: Turn this function into a method on `Fireworks`. + fn add_rockets(&mut self, rockets: usize) { + self.rockets += rockets + } + + // TODO: Turn this function into a method on `Fireworks`. + fn start(self) -> String { + "🚀".repeat(self.rockets) + } } + fn main() { // You can optionally experiment here. } diff --git a/exercises/08_enums/enums1.rs b/exercises/08_enums/enums1.rs index c0d0c308d2..1aa6af37bf 100644 --- a/exercises/08_enums/enums1.rs +++ b/exercises/08_enums/enums1.rs @@ -1,6 +1,11 @@ #[derive(Debug)] enum Message { // TODO: Define a few types of messages as used below. + Resize, + Move, + Echo, + ChangeColor, + Quit } fn main() { diff --git a/exercises/08_enums/enums2.rs b/exercises/08_enums/enums2.rs index d70f6398d1..0f36faf2a3 100644 --- a/exercises/08_enums/enums2.rs +++ b/exercises/08_enums/enums2.rs @@ -7,6 +7,11 @@ struct Point { #[derive(Debug)] enum Message { // TODO: Define the different variants used below. + Resize { width: u8, height: u8 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit } impl Message { diff --git a/exercises/08_enums/enums3.rs b/exercises/08_enums/enums3.rs index cb05f657c2..d15242633d 100644 --- a/exercises/08_enums/enums3.rs +++ b/exercises/08_enums/enums3.rs @@ -46,6 +46,13 @@ impl State { fn process(&mut self, message: Message) { // TODO: Create a match expression to process the different message // variants using the methods defined above. + match message { + Message::Resize { width, height } => self.resize(width, height), + Message::Move (point) => self.move_position(point), + Message::Echo (s) => self.echo(s), + Message::ChangeColor (r, g, b) => self.change_color(r,g,b), + Message::Quit => self.quit() + } } } diff --git a/exercises/09_strings/strings1.rs b/exercises/09_strings/strings1.rs index 6abdbb48f0..06755aae40 100644 --- a/exercises/09_strings/strings1.rs +++ b/exercises/09_strings/strings1.rs @@ -1,6 +1,6 @@ // TODO: Fix the compiler error without changing the function signature. fn current_favorite_color() -> String { - "blue" + "blue".to_string() } fn main() { diff --git a/exercises/09_strings/strings2.rs b/exercises/09_strings/strings2.rs index 93d9cb6b7f..2ed89c5666 100644 --- a/exercises/09_strings/strings2.rs +++ b/exercises/09_strings/strings2.rs @@ -6,7 +6,7 @@ fn is_a_color_word(attempt: &str) -> bool { fn main() { let word = String::from("green"); // Don't change 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/09_strings/strings3.rs b/exercises/09_strings/strings3.rs index f5e45b0ffc..1eed4327c1 100644 --- a/exercises/09_strings/strings3.rs +++ b/exercises/09_strings/strings3.rs @@ -1,13 +1,15 @@ fn trim_me(input: &str) -> &str { - // TODO: Remove whitespace from both ends of a string. + input.trim() } fn compose_me(input: &str) -> String { // TODO: Add " world!" to the string! There are multiple ways to do this. + format!("{} world!", &input) } fn replace_me(input: &str) -> String { // TODO: Replace "cars" in the string with "balloons". + input.replace("cars", "balloons") } fn main() { diff --git a/exercises/09_strings/strings4.rs b/exercises/09_strings/strings4.rs index 43976a6403..00942ceeac 100644 --- a/exercises/09_strings/strings4.rs +++ b/exercises/09_strings/strings4.rs @@ -13,23 +13,23 @@ fn string(arg: String) { // Your task is to replace `placeholder(…)` with either `string_slice(…)` // or `string(…)` depending on what you think each value is. fn main() { - placeholder("blue"); + string_slice("blue"); - placeholder("red".to_string()); + string("red".to_string()); - placeholder(String::from("hi")); + string(String::from("hi")); - placeholder("rust is fun!".to_owned()); + string("rust is fun!".to_owned()); - placeholder(format!("Interpolation {}", "Station")); + string(format!("Interpolation {}", "Station")); // WARNING: This is byte indexing, not character indexing. // Character indexing can be done using `s.chars().nth(INDEX)`. - placeholder(&String::from("abc")[0..1]); + string_slice(&String::from("abc")[0..1]); - placeholder(" hello there ".trim()); + string_slice(" hello there ".trim()); - placeholder("Happy Monday!".replace("Mon", "Tues")); + string("Happy Monday!".replace("Mon", "Tues")); - placeholder("mY sHiFt KeY iS sTiCkY".to_lowercase()); + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); } diff --git a/exercises/10_modules/modules1.rs b/exercises/10_modules/modules1.rs index d97ab23a53..81981dfca5 100644 --- a/exercises/10_modules/modules1.rs +++ b/exercises/10_modules/modules1.rs @@ -5,7 +5,7 @@ mod sausage_factory { String::from("Ginger") } - fn make_sausage() { + pub fn make_sausage() { get_secret_recipe(); println!("sausage!"); } diff --git a/exercises/10_modules/modules2.rs b/exercises/10_modules/modules2.rs index 782a70eace..177d8954bb 100644 --- a/exercises/10_modules/modules2.rs +++ b/exercises/10_modules/modules2.rs @@ -6,6 +6,9 @@ mod delicious_snacks { // 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: &str = "Pear"; pub const APPLE: &str = "Apple"; @@ -17,6 +20,8 @@ mod delicious_snacks { } } + + fn main() { println!( "favorite snacks: {} and {}", diff --git a/exercises/10_modules/modules3.rs b/exercises/10_modules/modules3.rs index 691608d275..403b7ea1d5 100644 --- a/exercises/10_modules/modules3.rs +++ b/exercises/10_modules/modules3.rs @@ -3,7 +3,7 @@ // TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into // your scope. Bonus style points if you can do it with one line! -// use ???; +use std::time::{SystemTime, UNIX_EPOCH}; fn main() { match SystemTime::now().duration_since(UNIX_EPOCH) { diff --git a/exercises/11_hashmaps/hashmaps1.rs b/exercises/11_hashmaps/hashmaps1.rs index 74001d0432..904e3cd676 100644 --- a/exercises/11_hashmaps/hashmaps1.rs +++ b/exercises/11_hashmaps/hashmaps1.rs @@ -8,12 +8,14 @@ use std::collections::HashMap; fn fruit_basket() -> HashMap { // TODO: Declare the hash map. - // let mut basket = + 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. + basket.insert(String::from("apple"), 5); + basket.insert(String::from("peach"), 5); basket } diff --git a/exercises/11_hashmaps/hashmaps2.rs b/exercises/11_hashmaps/hashmaps2.rs index e9f53fea3c..025be06c2d 100644 --- a/exercises/11_hashmaps/hashmaps2.rs +++ b/exercises/11_hashmaps/hashmaps2.rs @@ -32,6 +32,8 @@ fn fruit_basket(basket: &mut HashMap) { // 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! + + basket.entry(fruit).or_insert(1); } } diff --git a/exercises/11_hashmaps/hashmaps3.rs b/exercises/11_hashmaps/hashmaps3.rs index ba5a0e70e6..21b86252c1 100644 --- a/exercises/11_hashmaps/hashmaps3.rs +++ b/exercises/11_hashmaps/hashmaps3.rs @@ -31,6 +31,14 @@ fn build_score_table(results: &str) -> HashMap<&str, TeamScores> { // Keep in mind that goals scored by team 1 will be the number of goals // conceded by team 2. Similarly, goals scored by team 2 will be the // number of goals conceded by team 1. + + let team_1 = scores.entry(team_1_name).or_default(); + team_1.goals_scored += team_1_score; + team_1.goals_conceded += team_2_score; + + let team_2 = scores.entry(team_2_name).or_default(); + team_2.goals_scored += team_2_score; + team_2.goals_conceded += team_1_score; } scores diff --git a/exercises/12_options/options1.rs b/exercises/12_options/options1.rs index d0c412a8d4..cb7aca2e83 100644 --- a/exercises/12_options/options1.rs +++ b/exercises/12_options/options1.rs @@ -4,6 +4,12 @@ // `hour_of_day` is higher than 23. fn maybe_ice_cream(hour_of_day: u16) -> Option { // TODO: Complete the function body. + + match hour_of_day { + 0..=21 => Some(5), + 22..=23 => Some(0), + _ => None, + } } fn main() { @@ -18,7 +24,7 @@ mod tests { fn raw_value() { // TODO: Fix this test. How do you get the value contained in the // Option? - let ice_creams = maybe_ice_cream(12); + let ice_creams = maybe_ice_cream(12).unwrap(); assert_eq!(ice_creams, 5); // Don't change this line. } diff --git a/exercises/12_options/options2.rs b/exercises/12_options/options2.rs index 07c27c6ec2..1039d61db4 100644 --- a/exercises/12_options/options2.rs +++ b/exercises/12_options/options2.rs @@ -10,7 +10,7 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if-let statement whose value is `Some`. - word = optional_target { + if let Some(word) = optional_target { assert_eq!(word, target); } } @@ -29,7 +29,7 @@ mod tests { // TODO: Make this a while-let statement. Remember that `Vec::pop()` // adds another layer of `Option`. You can do nested pattern matching // in if-let and while-let statements. - integer = optional_integers.pop() { + while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, cursor); cursor -= 1; } diff --git a/exercises/12_options/options3.rs b/exercises/12_options/options3.rs index c97b1d3cf4..aecb7a57cd 100644 --- a/exercises/12_options/options3.rs +++ b/exercises/12_options/options3.rs @@ -9,7 +9,7 @@ fn main() { // TODO: Fix the compiler error by adding something to this match statement. match optional_point { - Some(p) => println!("Coordinates are {},{}", p.x, p.y), + Some(ref p) => println!("Coordinates are {},{}", p.x, p.y), _ => panic!("No match!"), } diff --git a/exercises/13_error_handling/errors1.rs b/exercises/13_error_handling/errors1.rs index e07fddc3cd..a2087cbc52 100644 --- a/exercises/13_error_handling/errors1.rs +++ b/exercises/13_error_handling/errors1.rs @@ -4,12 +4,11 @@ // construct to `Option` that can be used to express error conditions. Change // the function signature and body to return `Result` instead // of `Option`. -fn generate_nametag_text(name: String) -> Option { +fn generate_nametag_text(name: String) -> Result { if name.is_empty() { - // Empty names aren't allowed - None + Err("Empty names aren't allowed".to_string()) } else { - Some(format!("Hi! My name is {name}")) + Ok(format!("Hi! My name is {name}")) } } diff --git a/exercises/13_error_handling/errors2.rs b/exercises/13_error_handling/errors2.rs index defe359b48..3d850f76b5 100644 --- a/exercises/13_error_handling/errors2.rs +++ b/exercises/13_error_handling/errors2.rs @@ -21,7 +21,7 @@ fn total_cost(item_quantity: &str) -> Result { let cost_per_item = 5; // TODO: Handle the error case as described above. - let qty = item_quantity.parse::(); + let qty = item_quantity.parse::()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/13_error_handling/errors3.rs b/exercises/13_error_handling/errors3.rs index 8e8c38a2a1..bf21bbc622 100644 --- a/exercises/13_error_handling/errors3.rs +++ b/exercises/13_error_handling/errors3.rs @@ -15,7 +15,7 @@ fn total_cost(item_quantity: &str) -> Result { // TODO: Fix the compiler error by changing the signature and body of the // `main` function. -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; @@ -28,4 +28,6 @@ fn main() { tokens -= cost; println!("You now have {tokens} tokens."); } + + Ok(()) } diff --git a/exercises/13_error_handling/errors4.rs b/exercises/13_error_handling/errors4.rs index 144fce7b22..3ce6edeffa 100644 --- a/exercises/13_error_handling/errors4.rs +++ b/exercises/13_error_handling/errors4.rs @@ -1,3 +1,5 @@ +use std::cmp::Ordering; + #[derive(PartialEq, Debug)] enum CreationError { Negative, @@ -11,7 +13,11 @@ impl PositiveNonzeroInteger { fn new(value: i64) -> Result { // TODO: This function shouldn't always return an `Ok`. // Read the tests below to clarify what should be returned. - Ok(Self(value as u64)) + match value.cmp(&0) { + Ordering::Less => Err(CreationError::Negative), + Ordering::Equal => Err(CreationError::Zero), + Ordering::Greater => Ok(Self(value as u64)), + } } } diff --git a/exercises/13_error_handling/errors5.rs b/exercises/13_error_handling/errors5.rs index 125779b867..d33d12e579 100644 --- a/exercises/13_error_handling/errors5.rs +++ b/exercises/13_error_handling/errors5.rs @@ -48,7 +48,7 @@ impl PositiveNonzeroInteger { // TODO: Add the correct return type `Result<(), Box>`. What can we // use to describe both errors? Is there a trait which both errors implement? -fn main() { +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/13_error_handling/errors6.rs b/exercises/13_error_handling/errors6.rs index 73055c794c..63db30224b 100644 --- a/exercises/13_error_handling/errors6.rs +++ b/exercises/13_error_handling/errors6.rs @@ -34,7 +34,7 @@ impl PositiveNonzeroInteger { fn parse(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(); + let x: i64 = s.parse().map_err(ParsePosNonzeroError::ParseInt)?; Self::new(x).map_err(ParsePosNonzeroError::Creation) } } diff --git a/exercises/14_generics/generics1.rs b/exercises/14_generics/generics1.rs index 87ed990b65..e13fd828f1 100644 --- a/exercises/14_generics/generics1.rs +++ b/exercises/14_generics/generics1.rs @@ -6,7 +6,7 @@ fn main() { // TODO: Fix the compiler error by annotating the type of the vector // `Vec`. Choose `T` as some integer type that can be created from // `u8` and `i8`. - let mut numbers = Vec::new(); + let mut numbers: Vec = Vec::new(); // Don't change the lines below. let n1: u8 = 42; diff --git a/exercises/14_generics/generics2.rs b/exercises/14_generics/generics2.rs index 8908725bf9..ba77625854 100644 --- a/exercises/14_generics/generics2.rs +++ b/exercises/14_generics/generics2.rs @@ -1,12 +1,12 @@ // This powerful wrapper provides the ability to store a positive integer value. // TODO: Rewrite it using a generic so that it supports wrapping ANY type. -struct Wrapper { - value: u32, +struct Wrapper { + value: T, } // TODO: Adapt the struct's implementation to be generic over the wrapped value. -impl Wrapper { - fn new(value: u32) -> Self { +impl Wrapper { + fn new(value: T) -> Self { Wrapper { value } } } diff --git a/exercises/15_traits/traits1.rs b/exercises/15_traits/traits1.rs index 85be17ea82..fad6a50892 100644 --- a/exercises/15_traits/traits1.rs +++ b/exercises/15_traits/traits1.rs @@ -6,6 +6,9 @@ trait AppendBar { impl AppendBar for String { // TODO: Implement `AppendBar` for the type `String`. + fn append_bar(self) -> Self { + self + "Bar" + } } fn main() { diff --git a/exercises/15_traits/traits2.rs b/exercises/15_traits/traits2.rs index d724dc288e..f608fe8957 100644 --- a/exercises/15_traits/traits2.rs +++ b/exercises/15_traits/traits2.rs @@ -5,6 +5,13 @@ trait AppendBar { // TODO: Implement the trait `AppendBar` for a vector of strings. // `append_bar` should push the string "Bar" into the vector. +impl AppendBar for Vec { + fn append_bar(mut self) -> Self { + self.push("Bar".to_string()); + self + } +} + fn main() { // You can optionally experiment here. } diff --git a/exercises/15_traits/traits3.rs b/exercises/15_traits/traits3.rs index c244650da6..144ac0a337 100644 --- a/exercises/15_traits/traits3.rs +++ b/exercises/15_traits/traits3.rs @@ -3,7 +3,9 @@ trait Licensed { // implementors like the two structs below can share that default behavior // without repeating the function. // The default license information should be the string "Default license". - fn licensing_info(&self) -> String; + fn licensing_info(&self) -> String { + String::from("Default license") + } } struct SomeSoftware { diff --git a/exercises/15_traits/traits4.rs b/exercises/15_traits/traits4.rs index 80092a6466..b23dcdda95 100644 --- a/exercises/15_traits/traits4.rs +++ b/exercises/15_traits/traits4.rs @@ -11,7 +11,7 @@ impl Licensed for SomeSoftware {} impl Licensed for OtherSoftware {} // TODO: Fix the compiler error by only changing the signature of this function. -fn compare_license_types(software1: ???, software2: ???) -> bool { +fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool { software1.licensing_info() == software2.licensing_info() } diff --git a/exercises/15_traits/traits5.rs b/exercises/15_traits/traits5.rs index 5b356ac738..f2fbdb121d 100644 --- a/exercises/15_traits/traits5.rs +++ b/exercises/15_traits/traits5.rs @@ -19,7 +19,7 @@ impl SomeTrait for OtherStruct {} impl OtherTrait for OtherStruct {} // TODO: Fix the compiler error by only changing the signature of this function. -fn some_func(item: ???) -> bool { +fn some_func(item: T) -> bool { item.some_function() && item.other_function() } diff --git a/exercises/16_lifetimes/lifetimes1.rs b/exercises/16_lifetimes/lifetimes1.rs index 19e2d398b5..683bd75592 100644 --- a/exercises/16_lifetimes/lifetimes1.rs +++ b/exercises/16_lifetimes/lifetimes1.rs @@ -4,7 +4,7 @@ // not own their own data. What if their owner goes out of scope? // TODO: Fix the compiler error by updating the function signature. -fn longest(x: &str, y: &str) -> &str { +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { diff --git a/exercises/16_lifetimes/lifetimes2.rs b/exercises/16_lifetimes/lifetimes2.rs index de5a5dfc79..e7893b76f1 100644 --- a/exercises/16_lifetimes/lifetimes2.rs +++ b/exercises/16_lifetimes/lifetimes2.rs @@ -15,6 +15,6 @@ fn main() { { let string2 = String::from("xyz"); result = longest(&string1, &string2); + println!("The longest string is '{result}'"); } - println!("The longest string is '{result}'"); } diff --git a/exercises/16_lifetimes/lifetimes3.rs b/exercises/16_lifetimes/lifetimes3.rs index 1cc27592c6..91e3922c26 100644 --- a/exercises/16_lifetimes/lifetimes3.rs +++ b/exercises/16_lifetimes/lifetimes3.rs @@ -1,9 +1,9 @@ // Lifetimes are also needed when structs hold references. // TODO: Fix the compiler errors about the struct. -struct Book { - author: &str, - title: &str, +struct Book<'a> { + author: &'a str, + title: &'a str, } fn main() { diff --git a/exercises/17_tests/tests1.rs b/exercises/17_tests/tests1.rs index 7529f9f049..97e65ccb5e 100644 --- a/exercises/17_tests/tests1.rs +++ b/exercises/17_tests/tests1.rs @@ -11,13 +11,15 @@ fn main() { #[cfg(test)] mod tests { + use crate::is_even; + // TODO: Import `is_even`. You can use a wildcard to import everything in // the outer module. #[test] fn you_can_assert() { // TODO: Test the function `is_even` with some values. - assert!(); - assert!(); + assert!(is_even(2)); + assert!(!is_even(1)); } } diff --git a/exercises/17_tests/tests2.rs b/exercises/17_tests/tests2.rs index 0c6573e8f0..5f97511645 100644 --- a/exercises/17_tests/tests2.rs +++ b/exercises/17_tests/tests2.rs @@ -15,9 +15,9 @@ mod tests { #[test] fn you_can_assert_eq() { // TODO: Test the function `power_of_2` with some values. - assert_eq!(); - assert_eq!(); - assert_eq!(); - assert_eq!(); + assert_eq!(power_of_2(2), 4); + assert_eq!(power_of_2(3), 8); + assert_eq!(power_of_2(4), 16); + assert_eq!(power_of_2(5), 32); } } diff --git a/exercises/17_tests/tests3.rs b/exercises/17_tests/tests3.rs index 822184ef75..085bb6239e 100644 --- a/exercises/17_tests/tests3.rs +++ b/exercises/17_tests/tests3.rs @@ -29,13 +29,14 @@ mod tests { // TODO: This test should check if the rectangle has the size that we // pass to its constructor. let rect = Rectangle::new(10, 20); - assert_eq!(todo!(), 10); // Check width - assert_eq!(todo!(), 20); // Check height + assert_eq!(rect.width, 10); // Check width + assert_eq!(rect.height, 20); // Check height } // TODO: This test should check if the program panics when we try to create // a rectangle with negative width. #[test] + #[should_panic] fn negative_width() { let _rect = Rectangle::new(-10, 10); } @@ -43,6 +44,7 @@ mod tests { // TODO: This test should check if the program panics when we try to create // a rectangle with negative height. #[test] + #[should_panic] fn negative_height() { let _rect = Rectangle::new(10, -10); } diff --git a/exercises/18_iterators/iterators1.rs b/exercises/18_iterators/iterators1.rs index 8014f0f1ca..8e0f56bf05 100644 --- a/exercises/18_iterators/iterators1.rs +++ b/exercises/18_iterators/iterators1.rs @@ -13,13 +13,13 @@ mod tests { let my_fav_fruits = &["banana", "custard apple", "avocado", "peach", "raspberry"]; // TODO: Create an iterator over the slice. - let mut fav_fruits_iterator = todo!(); + let mut fav_fruits_iterator = my_fav_fruits.iter(); assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); - assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // TODO: Replace `todo!()` assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); - assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // TODO: Replace `todo!()` assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); - assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), None); // TODO: Replace `todo!()` } } diff --git a/exercises/18_iterators/iterators2.rs b/exercises/18_iterators/iterators2.rs index 5903e657e9..d86fb1e531 100644 --- a/exercises/18_iterators/iterators2.rs +++ b/exercises/18_iterators/iterators2.rs @@ -7,7 +7,7 @@ fn capitalize_first(input: &str) -> String { let mut chars = input.chars(); match chars.next() { None => String::new(), - Some(first) => todo!(), + Some(first) => first.to_uppercase().to_string() + chars.as_str(), } } @@ -15,14 +15,14 @@ fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] fn capitalize_words_vector(words: &[&str]) -> Vec { - // ??? + words.iter().map(|x| capitalize_first(x)).collect() } // TODO: Apply the `capitalize_first` function again to a slice of string // slices. Return a single string. // ["hello", " ", "world"] -> "Hello World" fn capitalize_words_string(words: &[&str]) -> String { - // ??? + words.iter().map(|x| capitalize_first(x)).collect() } fn main() { diff --git a/exercises/18_iterators/iterators3.rs b/exercises/18_iterators/iterators3.rs index dce09055dd..3e7cfa6af3 100644 --- a/exercises/18_iterators/iterators3.rs +++ b/exercises/18_iterators/iterators3.rs @@ -11,23 +11,35 @@ enum DivisionError { // TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Otherwise, return a suitable error. fn divide(a: i64, b: i64) -> Result { - todo!(); + if b == 0 { + return Err(DivisionError::DivideByZero); + } else if a == i64::MIN && b == -1 { + return Err(DivisionError::IntegerOverflow); + } else if a % b != 0 { + return Err(DivisionError::NotDivisible) + } + + Ok(a / b) } -// TODO: Add the correct return type and complete the function body. -// Desired output: `Ok([1, 11, 1426, 3])` -fn result_with_list() { +fn result_with_list() -> Result, DivisionError> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ let numbers = [27, 297, 38502, 81]; let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // Collects to the expected return type. Returns the first error in the + // division results (if one exists). + division_results.collect() } -// TODO: Add the correct return type and complete the function body. -// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]` -fn list_of_results() { +fn list_of_results() -> Vec> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ let numbers = [27, 297, 38502, 81]; let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // Collects to the expected return type. + division_results.collect() } + fn main() { // You can optionally experiment here. } diff --git a/exercises/18_iterators/iterators4.rs b/exercises/18_iterators/iterators4.rs index c296f0e426..c497cd313d 100644 --- a/exercises/18_iterators/iterators4.rs +++ b/exercises/18_iterators/iterators4.rs @@ -10,6 +10,8 @@ fn factorial(num: u64) -> u64 { // - additional variables // For an extra challenge, don't use: // - recursion + + (2..=num).product() } fn main() { diff --git a/exercises/18_iterators/iterators5.rs b/exercises/18_iterators/iterators5.rs index 08f292d7e7..83d22cf675 100644 --- a/exercises/18_iterators/iterators5.rs +++ b/exercises/18_iterators/iterators5.rs @@ -28,6 +28,8 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // `map` is a hash map with `String` keys and `Progress` values. // map = { "variables1": Complete, "conversions3": None, … } + + map.values().filter(|x| **x == value).count() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -48,6 +50,11 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // `collection` is a slice of hash maps. // collection = [{ "variables1": Complete, "conversions3": None, … }, // { "variables2": Complete, … }, … ] + + collection + .iter() + .map(|map| count_iterator(map, value)) + .sum() } fn main() { diff --git a/exercises/19_smart_pointers/smart_pointers1.rs b/exercises/19_smart_pointers/smart_pointers1.rs index d70e1c3d39..35bd5f8394 100644 --- a/exercises/19_smart_pointers/smart_pointers1.rs +++ b/exercises/19_smart_pointers/smart_pointers1.rs @@ -10,20 +10,23 @@ // the next item. The last item is a value called `Nil`. // TODO: Use a `Box` in the enum definition to make the code compile. + +use crate::List::{Cons, Nil}; + #[derive(PartialEq, Debug)] enum List { - Cons(i32, List), + Cons(i32, Box), Nil, } // TODO: Create an empty cons list. fn create_empty_list() -> List { - todo!() + List::Nil } // TODO: Create a non-empty cons list. fn create_non_empty_list() -> List { - todo!() + Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(List::Nil)))))) } fn main() { diff --git a/exercises/19_smart_pointers/smart_pointers2.rs b/exercises/19_smart_pointers/smart_pointers2.rs index ecd3438701..8df0d2643e 100644 --- a/exercises/19_smart_pointers/smart_pointers2.rs +++ b/exercises/19_smart_pointers/smart_pointers2.rs @@ -26,9 +26,7 @@ impl Planet { } } -fn main() { - // You can optionally experiment here. -} +fn main() {} #[cfg(test)] mod tests { @@ -60,17 +58,17 @@ mod tests { jupiter.details(); // TODO - let saturn = Planet::Saturn(Rc::new(Sun)); + let saturn = Planet::Saturn(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 7 references saturn.details(); // TODO - let uranus = Planet::Uranus(Rc::new(Sun)); + let uranus = Planet::Uranus(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 8 references uranus.details(); // TODO - let neptune = Planet::Neptune(Rc::new(Sun)); + let neptune = Planet::Neptune(Rc::clone(&sun)); println!("reference count = {}", Rc::strong_count(&sun)); // 9 references neptune.details(); @@ -91,13 +89,13 @@ mod tests { drop(mars); println!("reference count = {}", Rc::strong_count(&sun)); // 4 references - // TODO + drop(earth); println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - // TODO + drop(venus); println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - // TODO + drop(mercury); println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference assert_eq!(Rc::strong_count(&sun), 1); diff --git a/exercises/19_smart_pointers/smart_pointers3.rs b/exercises/19_smart_pointers/smart_pointers3.rs index 6bb860f93f..a5b9467231 100644 --- a/exercises/19_smart_pointers/smart_pointers3.rs +++ b/exercises/19_smart_pointers/smart_pointers3.rs @@ -23,13 +23,13 @@ fn main() { let numbers: Vec<_> = (0..100u32).collect(); // TODO: Define `shared_numbers` by using `Arc`. - // let shared_numbers = ???; + let shared_numbers = Arc::new(numbers); let mut join_handles = Vec::new(); for offset in 0..8 { // TODO: Define `child_numbers` using `shared_numbers`. - // let child_numbers = ???; + let child_numbers = Arc::clone(&shared_numbers); let handle = thread::spawn(move || { let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); diff --git a/exercises/19_smart_pointers/smart_pointers4.rs b/exercises/19_smart_pointers/smart_pointers4.rs index 1566500716..0c9c1d6acd 100644 --- a/exercises/19_smart_pointers/smart_pointers4.rs +++ b/exercises/19_smart_pointers/smart_pointers4.rs @@ -39,7 +39,7 @@ mod tests { let mut input = Cow::from(&vec); abs_all(&mut input); // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. - assert!(matches!(input, todo!())); + assert!(matches!(input, Cow::Borrowed(_))); } #[test] @@ -52,7 +52,7 @@ mod tests { let mut input = Cow::from(vec); abs_all(&mut input); // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. - assert!(matches!(input, todo!())); + assert!(matches!(input, Cow::Owned(_))); } #[test] @@ -64,6 +64,6 @@ mod tests { let mut input = Cow::from(vec); abs_all(&mut input); // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. - assert!(matches!(input, todo!())); + assert!(matches!(input, Cow::Owned(_))); } } diff --git a/exercises/quizzes/quiz1.rs b/exercises/quizzes/quiz1.rs index 04fb2aaf8d..3eaf26f5db 100644 --- a/exercises/quizzes/quiz1.rs +++ b/exercises/quizzes/quiz1.rs @@ -10,7 +10,13 @@ // TODO: Write a function that calculates the price of an order of apples given // the quantity bought. -// fn calculate_price_of_apples(???) -> ??? { ??? } +fn calculate_price_of_apples(number_of_apples: i32) -> i64 { + if number_of_apples > 40 { + return i64::from(number_of_apples); + } + + return i64::from(number_of_apples * 2); + } fn main() { // You can optionally experiment here. diff --git a/exercises/quizzes/quiz2.rs b/exercises/quizzes/quiz2.rs index 2cddba907e..7c9af56842 100644 --- a/exercises/quizzes/quiz2.rs +++ b/exercises/quizzes/quiz2.rs @@ -27,7 +27,20 @@ mod my_module { use super::Command; // TODO: Complete the function as described above. - // pub fn transformer(input: ???) -> ??? { ??? } + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut output = Vec::new(); + + for (string, command) in input { + let result = match command { + Command::Uppercase => {string.to_uppercase()}, + Command::Trim => {string.trim().to_string()}, + Command::Append(number) => {string + &"bar".repeat(number)} + }; + output.push(result); + } + + output + } } fn main() { @@ -37,7 +50,7 @@ fn main() { #[cfg(test)] mod tests { // TODO: What do we need to import to have `transformer` in scope? - // use ???; + use crate::my_module::transformer; use super::Command; #[test] diff --git a/exercises/quizzes/quiz3.rs b/exercises/quizzes/quiz3.rs index c877c5f8e6..fdd4735aed 100644 --- a/exercises/quizzes/quiz3.rs +++ b/exercises/quizzes/quiz3.rs @@ -12,14 +12,16 @@ // block to support alphabetical report cards in addition to numerical ones. // TODO: Adjust the struct as described above. -struct ReportCard { - grade: f32, +struct ReportCard { + grade: T, student_name: String, student_age: u8, } +use std::fmt::Display; + // TODO: Adjust the impl block as described above. -impl ReportCard { +impl ReportCard { fn print(&self) -> String { format!( "{} ({}) - achieved a grade of {}",