diff --git a/exercises/00_intro/intro2.rs b/exercises/00_intro/intro2.rs index c6cb6451..03e376ed 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/README.md b/exercises/01_variables/README.md index 5ba2efca..7964ff29 100644 --- a/exercises/01_variables/README.md +++ b/exercises/01_variables/README.md @@ -1,7 +1,7 @@ # Variables In Rust, variables are immutable by default. -When a variable is immutable, once a value is bound to a name, you can't change that value. +When a variable is immutable, once a value is bound to a name, you can’t change that value. You can make them mutable by adding `mut` in front of the variable name. ## Further information diff --git a/exercises/01_variables/variables1.rs b/exercises/01_variables/variables1.rs index f83b44d4..ec1bcacb 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 e2a36035..2ee9d7e2 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 = 5; if x == 10 { println!("x is ten!"); diff --git a/exercises/01_variables/variables3.rs b/exercises/01_variables/variables3.rs index 06f35bb1..8724e03c 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=5; println!("Number {x}"); } diff --git a/exercises/01_variables/variables4.rs b/exercises/01_variables/variables4.rs index 6c138b18..9c49fad8 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 cf5620da..3ceae2dd 100644 --- a/exercises/01_variables/variables5.rs +++ b/exercises/01_variables/variables5.rs @@ -1,8 +1,8 @@ fn main() { let number = "T-H-R-E-E"; // Don't change this line - println!("Spell a number: {number}"); + println!("Spell a number: {number}" ); // TODO: Fix the compiler error by changing the line below without renaming the variable. - number = 3; + let number = 5; println!("Number plus two is: {}", number + 2); } diff --git a/exercises/01_variables/variables6.rs b/exercises/01_variables/variables6.rs index 4a040fdd..6b50bbff 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:u8 = 3; fn main() { println!("Number: {NUMBER}"); diff --git a/exercises/02_functions/functions1.rs b/exercises/02_functions/functions1.rs index a812c21b..a87707a7 100644 --- a/exercises/02_functions/functions1.rs +++ b/exercises/02_functions/functions1.rs @@ -1,5 +1,6 @@ // 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 2c773c6b..fe36fee8 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 8d654772..b234db2a 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(8); } diff --git a/exercises/02_functions/functions4.rs b/exercises/02_functions/functions4.rs index b22bffda..60ab17d4 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 34a2ac7d..c92d17cb 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 e5a3c5a5..babe32d4 100644 --- a/exercises/03_if/if1.rs +++ b/exercises/03_if/if1.rs @@ -4,6 +4,12 @@ fn bigger(a: i32, b: i32) -> i32 { // Do not use: // - another function call // - additional variables + if a > b { + return a; + } else if a < b { + return b; + } + a } fn main() { diff --git a/exercises/03_if/if2.rs b/exercises/03_if/if2.rs index ca8493cc..a6bcce53 100644 --- a/exercises/03_if/if2.rs +++ b/exercises/03_if/if2.rs @@ -2,8 +2,10 @@ fn picky_eater(food: &str) -> &str { if food == "strawberry" { "Yummy!" - } else { - 1 + } else if food=="potato"{ + "I guess I can eat that." + }else { + "No thanks!" } } @@ -19,7 +21,7 @@ mod tests { #[test] fn yummy_food() { - // This means that calling `picky_eater` with the argument "strawberry" should return "Yummy!". + // This means that calling `picky_eater` with the argument "food" should return "Yummy!". assert_eq!(picky_eater("strawberry"), "Yummy!"); } diff --git a/exercises/03_if/if3.rs b/exercises/03_if/if3.rs index 89164eb2..6d7a7f40 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 84923c75..8ee86e1d 100644 --- a/exercises/04_primitive_types/primitive_types1.rs +++ b/exercises/04_primitive_types/primitive_types1.rs @@ -9,6 +9,8 @@ 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 14018475..ab07fecf 100644 --- a/exercises/04_primitive_types/primitive_types2.rs +++ b/exercises/04_primitive_types/primitive_types2.rs @@ -17,7 +17,7 @@ fn main() { // 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 = '*'; if your_character.is_alphabetic() { println!("Alphabetical!"); } else if your_character.is_numeric() { diff --git a/exercises/04_primitive_types/primitive_types3.rs b/exercises/04_primitive_types/primitive_types3.rs index 9b79c0cf..4bf62a7f 100644 --- a/exercises/04_primitive_types/primitive_types3.rs +++ b/exercises/04_primitive_types/primitive_types3.rs @@ -1,7 +1,7 @@ fn main() { // TODO: Create an array called `a` with at least 100 elements in it. // let a = ??? - + let a=[1;101]; if a.len() >= 100 { println!("Wow, that's a big array!"); } else { diff --git a/exercises/04_primitive_types/primitive_types4.rs b/exercises/04_primitive_types/primitive_types4.rs index 16e4fd93..a15feb1c 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 6e00ef51..a49175c1 100644 --- a/exercises/04_primitive_types/primitive_types5.rs +++ b/exercises/04_primitive_types/primitive_types5.rs @@ -3,6 +3,6 @@ fn main() { // 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 a97e5311..b886d829 100644 --- a/exercises/04_primitive_types/primitive_types6.rs +++ b/exercises/04_primitive_types/primitive_types6.rs @@ -1,5 +1,6 @@ fn main() { // You can optionally experiment here. + } #[cfg(test)] @@ -11,7 +12,8 @@ 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 68e1affa..56bc77e4 100644 --- a/exercises/05_vecs/vecs1.rs +++ b/exercises/05_vecs/vecs1.rs @@ -3,7 +3,7 @@ fn array_and_vec() -> ([i32; 4], Vec) { // TODO: Create a vector called `v` which contains the exact same elements as in the array `a`. // Use the vector macro. - // let v = ???; + let v: Vec = a.into_iter().collect(); (a, v) } diff --git a/exercises/05_vecs/vecs2.rs b/exercises/05_vecs/vecs2.rs index a9be2580..bcd45ea1 100644 --- a/exercises/05_vecs/vecs2.rs +++ b/exercises/05_vecs/vecs2.rs @@ -1,9 +1,10 @@ fn vec_loop(input: &[i32]) -> Vec { - let mut output = Vec::new(); + let mut output: Vec = Vec::new(); 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 @@ -24,7 +25,7 @@ fn vec_map(input: &[i32]) -> Vec { input .iter() .map(|element| { - // ??? + element*2 }) .collect() } diff --git a/exercises/06_move_semantics/move_semantics1.rs b/exercises/06_move_semantics/move_semantics1.rs index 4eb3d618..bf559432 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 a3ab7a0f..e205b813 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 11dbbbeb..4a90c211 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 56da988c..89b412f0 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 cd0dafd0..efa06f7a 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,8 @@ 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 959c4c6a..534b6242 100644 --- a/exercises/07_structs/structs1.rs +++ b/exercises/07_structs/structs1.rs @@ -1,9 +1,16 @@ 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 +26,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 +36,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 +46,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 79141af9..167089ce 100644 --- a/exercises/07_structs/structs2.rs +++ b/exercises/07_structs/structs2.rs @@ -21,6 +21,20 @@ fn create_order_template() -> Order { } } +impl Order { + fn create_orders(name:String,year:u32,made_by_phone:bool,made_by_mobile:bool,made_by_email:bool,item_number:u32,count:u32) -> Order { + Order { + name, + year, + made_by_phone, + made_by_mobile, + made_by_email, + item_number, + count, + } + } +} + fn main() { // You can optionally experiment here. } @@ -34,7 +48,8 @@ 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::create_orders("Hacker in Rust".to_string(), order_template.year, order_template.made_by_phone, + order_template.made_by_mobile, order_template.made_by_email, order_template.item_number, 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 69e5ced7..9ccaa742 100644 --- a/exercises/07_structs/structs3.rs +++ b/exercises/07_structs/structs3.rs @@ -15,7 +15,7 @@ impl Package { // learn about error handling later. panic!("Can't ship a package with weight below 10 grams"); } - + Self { sender_country, recipient_country, @@ -24,14 +24,17 @@ impl Package { } // TODO: Add the correct return type to the function signature. - fn is_international(&self) { + fn is_international(&self)->bool { // TODO: Read the tests that use this method to find out when a package // is considered international. + self.recipient_country != self.sender_country } // TODO: Add the correct return type to the function signature. - fn get_fees(&self, cents_per_gram: u32) { + fn get_fees(&self, cents_per_gram: u32)->u32 { // TODO: Calculate the package's fees. + + self.weight_in_grams*cents_per_gram } } diff --git a/exercises/08_enums/README.md b/exercises/08_enums/README.md index b05cb422..30d4d91d 100644 --- a/exercises/08_enums/README.md +++ b/exercises/08_enums/README.md @@ -1,10 +1,10 @@ # Enums Rust allows you to define types called "enums" which enumerate possible values. -Enums are a feature in many languages, but their capabilities differ in each language. Rust's enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell. +Enums are a feature in many languages, but their capabilities differ in each language. Rust’s enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell. Useful in combination with enums is Rust's "pattern matching" facility, which makes it easy to run different code for different values of an enumeration. ## Further information - [Enums](https://doc.rust-lang.org/book/ch06-00-enums.html) -- [Pattern syntax](https://doc.rust-lang.org/book/ch19-03-pattern-syntax.html) +- [Pattern syntax](https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html) diff --git a/exercises/08_enums/enums1.rs b/exercises/08_enums/enums1.rs index c0d0c308..635a3349 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 d70f6398..07aee262 100644 --- a/exercises/08_enums/enums2.rs +++ b/exercises/08_enums/enums2.rs @@ -6,7 +6,11 @@ struct Point { #[derive(Debug)] enum Message { - // TODO: Define the different variants used below. + Resize { width: u64, height: u64 }, + 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 cb05f657..9aa25076 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 } => State::resize(self, width, height), + Message::Move(point) => State::move_position(self, point), + Message::Echo(s) => State::echo(self, s), + Message::ChangeColor(r, g, b) => State::change_color(self, r, g, b), + Message::Quit => State::quit(self), + } } } diff --git a/exercises/09_strings/strings1.rs b/exercises/09_strings/strings1.rs index 6abdbb48..06755aae 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 93d9cb6b..9e605a68 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.as_str()) { 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 f5e45b0f..0dec1ca7 100644 --- a/exercises/09_strings/strings3.rs +++ b/exercises/09_strings/strings3.rs @@ -1,13 +1,16 @@ 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. + input.to_string() + " world!" } fn replace_me(input: &str) -> String { // TODO: Replace "cars" in the string with "balloons". + input.replace("cars", "balloons") } fn main() { @@ -23,7 +26,6 @@ mod tests { assert_eq!(trim_me("Hello! "), "Hello!"); assert_eq!(trim_me(" What's up!"), "What's up!"); assert_eq!(trim_me(" Hola! "), "Hola!"); - assert_eq!(trim_me("Hi!"), "Hi!"); } #[test] diff --git a/exercises/09_strings/strings4.rs b/exercises/09_strings/strings4.rs index 47307263..9d5dbce2 100644 --- a/exercises/09_strings/strings4.rs +++ b/exercises/09_strings/strings4.rs @@ -13,25 +13,25 @@ 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("nice weather".into()); + string_slice("nice weather"); - 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 d97ab23a..89668df1 100644 --- a/exercises/10_modules/modules1.rs +++ b/exercises/10_modules/modules1.rs @@ -1,12 +1,12 @@ // TODO: Fix the compiler error about calling a private function. mod sausage_factory { // Don't let anybody outside of this module see this! - fn get_secret_recipe() -> String { + fn _get_secret_recipe() -> String { String::from("Ginger") } - fn make_sausage() { - get_secret_recipe(); + pub fn make_sausage() { + _get_secret_recipe(); println!("sausage!"); } } diff --git a/exercises/10_modules/modules2.rs b/exercises/10_modules/modules2.rs index 782a70ea..14c03751 100644 --- a/exercises/10_modules/modules2.rs +++ b/exercises/10_modules/modules2.rs @@ -3,8 +3,8 @@ mod delicious_snacks { // TODO: Add the following two `use` statements after fixing them. - // 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"; @@ -18,6 +18,8 @@ mod delicious_snacks { } fn main() { + + use delicious_snacks; println!( "favorite snacks: {} and {}", delicious_snacks::fruit, diff --git a/exercises/10_modules/modules3.rs b/exercises/10_modules/modules3.rs index 691608d2..7ecb0048 100644 --- a/exercises/10_modules/modules3.rs +++ b/exercises/10_modules/modules3.rs @@ -5,7 +5,9 @@ // 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) { Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), Err(_) => panic!("SystemTime before UNIX EPOCH!"), diff --git a/exercises/11_hashmaps/hashmaps1.rs b/exercises/11_hashmaps/hashmaps1.rs index 74001d04..aa8c60ed 100644 --- a/exercises/11_hashmaps/hashmaps1.rs +++ b/exercises/11_hashmaps/hashmaps1.rs @@ -8,18 +8,26 @@ 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); + basket.insert("banana".to_string(), 2); // TODO: Put more fruits in your basket. + basket.insert("apples".to_string(), 2); + basket.insert("watermelon".to_string(), 2); + basket.insert("pinapple".to_string(), 2); + basket.insert("papaya".to_string(), 2); basket } fn main() { // You can optionally experiment here. + let a=vec![1,2,3]; + let b = a.into_iter().sum::(); + + print!("{b}") } #[cfg(test)] @@ -35,6 +43,6 @@ mod tests { #[test] fn at_least_five_fruits() { let basket = fruit_basket(); - assert!(basket.values().sum::() >= 5); + assert!(basket.into_values().sum::() >= 5); } } diff --git a/exercises/11_hashmaps/hashmaps2.rs b/exercises/11_hashmaps/hashmaps2.rs index e9f53fea..4b2d4ecd 100644 --- a/exercises/11_hashmaps/hashmaps2.rs +++ b/exercises/11_hashmaps/hashmaps2.rs @@ -32,6 +32,11 @@ 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! + match basket.get(&fruit) { + Some(_) => {}, + None => { basket.insert(fruit, 1); }, + } + } } diff --git a/exercises/11_hashmaps/hashmaps3.rs b/exercises/11_hashmaps/hashmaps3.rs index 5b390ab9..9f2e9bde 100644 --- a/exercises/11_hashmaps/hashmaps3.rs +++ b/exercises/11_hashmaps/hashmaps3.rs @@ -6,10 +6,10 @@ // number of goals the team scored, and the total number of goals the team // conceded. -use std::collections::HashMap; +use std::{collections::HashMap}; // A structure to store the goal details of a team. -#[derive(Default)] +#[derive(Default,Debug)] struct TeamScores { goals_scored: u8, goals_conceded: u8, @@ -31,6 +31,14 @@ fn build_scores_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. + scores.entry(team_1_name) + .and_modify(|a| + {a.goals_scored+=team_1_score ; a.goals_conceded+=team_2_score} + ).or_insert(TeamScores { goals_scored: team_1_score, goals_conceded: team_2_score }); + scores.entry(team_2_name) + .and_modify(|a| + {a.goals_scored+=team_2_score ; a.goals_conceded+= team_1_score}) + .or_insert(TeamScores { goals_scored: team_2_score, goals_conceded: team_1_score }); } scores @@ -38,6 +46,19 @@ fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { fn main() { // You can optionally experiment here. + + const RESULTS: &str = "England,France,4,2 + France,Italy,3,1 + Poland,Spain,2,0 + Germany,England,2,1 + England,Spain,1,0"; + + let mut scores = HashMap::<&str, TeamScores>::new(); + + scores.entry("test").or_default(); + scores.entry("test2").and_modify(|a| { a.goals_conceded += 1; }); + print!("{scores:?}") + } #[cfg(test)] diff --git a/exercises/12_options/options1.rs b/exercises/12_options/options1.rs index d0c412a8..5755dfb5 100644 --- a/exercises/12_options/options1.rs +++ b/exercises/12_options/options1.rs @@ -1,9 +1,15 @@ -// This function returns how much ice cream there is left in the fridge. +// This function returns how much icecream there is left in the fridge. // If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, -// someone eats it all, so no ice cream is left (value 0). Return `None` if +// someone eats it all, so no icecream is left (value 0). Return `None` if // `hour_of_day` is higher than 23. -fn maybe_ice_cream(hour_of_day: u16) -> Option { +fn maybe_icecream(hour_of_day: u16) -> Option { // TODO: Complete the function body. + + match hour_of_day { + 0..22 => Some(5), + 22..24=>Some(0), + _=>None, + } } fn main() { @@ -18,19 +24,19 @@ 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 icecreams = maybe_icecream(12).unwrap(); - assert_eq!(ice_creams, 5); // Don't change this line. + assert_eq!(icecreams, 5); // Don't change this line. } #[test] - fn check_ice_cream() { - assert_eq!(maybe_ice_cream(0), Some(5)); - assert_eq!(maybe_ice_cream(9), Some(5)); - assert_eq!(maybe_ice_cream(18), Some(5)); - assert_eq!(maybe_ice_cream(22), Some(0)); - assert_eq!(maybe_ice_cream(23), Some(0)); - assert_eq!(maybe_ice_cream(24), None); - assert_eq!(maybe_ice_cream(25), None); + fn check_icecream() { + assert_eq!(maybe_icecream(0), Some(5)); + assert_eq!(maybe_icecream(9), Some(5)); + assert_eq!(maybe_icecream(18), Some(5)); + assert_eq!(maybe_icecream(22), Some(0)); + assert_eq!(maybe_icecream(23), Some(0)); + assert_eq!(maybe_icecream(24), None); + assert_eq!(maybe_icecream(25), None); } } diff --git a/exercises/12_options/options2.rs b/exercises/12_options/options2.rs index 07c27c6e..1039d61d 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 c97b1d3c..c468e1d6 100644 --- a/exercises/12_options/options3.rs +++ b/exercises/12_options/options3.rs @@ -8,8 +8,8 @@ fn main() { let optional_point = Some(Point { x: 100, y: 200 }); // TODO: Fix the compiler error by adding something to this match statement. - match optional_point { - Some(p) => println!("Coordinates are {},{}", p.x, p.y), + match &optional_point { + Some(p) => println!("Co-ordinates are {},{}", p.x, p.y), _ => panic!("No match!"), } diff --git a/exercises/13_error_handling/README.md b/exercises/13_error_handling/README.md index 9b6674bc..3b21f2b7 100644 --- a/exercises/13_error_handling/README.md +++ b/exercises/13_error_handling/README.md @@ -1,8 +1,8 @@ # Error handling -Most errors aren't serious enough to require the program to stop entirely. -Sometimes, when a function fails, it's for a reason that you can easily interpret and respond to. -For example, if you try to open a file and that operation fails because the file doesn't exist, you might want to create the file instead of terminating the process. +Most errors aren’t serious enough to require the program to stop entirely. +Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. +For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process. ## Further information diff --git a/exercises/13_error_handling/errors1.rs b/exercises/13_error_handling/errors1.rs index e07fddc3..afabeda8 100644 --- a/exercises/13_error_handling/errors1.rs +++ b/exercises/13_error_handling/errors1.rs @@ -4,12 +4,12 @@ // 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(format!("Empty names aren't allowed")) } 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 defe359b..578e9ff0 100644 --- a/exercises/13_error_handling/errors2.rs +++ b/exercises/13_error_handling/errors2.rs @@ -21,7 +21,8 @@ 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 8e8c38a2..98a0408d 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,7 @@ 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 ba01e54b..11d0e1df 100644 --- a/exercises/13_error_handling/errors4.rs +++ b/exercises/13_error_handling/errors4.rs @@ -9,8 +9,14 @@ struct PositiveNonzeroInteger(u64); impl PositiveNonzeroInteger { fn new(value: i64) -> Result { + // TODO: This function shouldn't always return an `Ok`. - Ok(Self(value as u64)) + + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(Self(x as u64)), + } } } diff --git a/exercises/13_error_handling/errors5.rs b/exercises/13_error_handling/errors5.rs index 125779b8..7b9019af 100644 --- a/exercises/13_error_handling/errors5.rs +++ b/exercises/13_error_handling/errors5.rs @@ -6,7 +6,7 @@ // // In short, this particular use case for boxes is for when you want to own a // value and you care only that it is a type which implements a particular -// trait. To do so, the `Box` is declared as of type `Box` where +// trait. To do so, The `Box` is declared as of type `Box` where // `Trait` is the trait the compiler looks for on any value used in that // context. For this exercise, that context is the potential errors which // can be returned in a `Result`. @@ -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 b1995e03..e6e7e707 100644 --- a/exercises/13_error_handling/errors6.rs +++ b/exercises/13_error_handling/errors6.rs @@ -25,7 +25,9 @@ impl ParsePosNonzeroError { } // TODO: Add another error conversion function here. - // fn from_parse_int(???) -> Self { ??? } + fn from_parse_int(err:ParseIntError) -> Self { + Self::ParseInt(err) + } } #[derive(PartialEq, Debug)] @@ -43,7 +45,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::from_parse_int)?; Self::new(x).map_err(ParsePosNonzeroError::from_creation) } } diff --git a/exercises/14_generics/generics1.rs b/exercises/14_generics/generics1.rs index 87ed990b..e13fd828 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 8908725b..ba776258 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/21_macros/README.md b/exercises/21_macros/README.md index de7fb7ba..337816d6 100644 --- a/exercises/21_macros/README.md +++ b/exercises/21_macros/README.md @@ -10,6 +10,5 @@ of exercises to Rustlings, but is all about learning to write Macros. ## Further information -- [The Rust Book - Macros](https://doc.rust-lang.org/book/ch20-05-macros.html) +- [Macros](https://doc.rust-lang.org/book/ch19-06-macros.html) - [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) -- [Rust by Example - macro_rules!](https://doc.rust-lang.org/rust-by-example/macros.html) diff --git a/exercises/22_clippy/clippy3.rs b/exercises/22_clippy/clippy3.rs index 7a3cb390..4f788349 100644 --- a/exercises/22_clippy/clippy3.rs +++ b/exercises/22_clippy/clippy3.rs @@ -4,11 +4,9 @@ #[rustfmt::skip] #[allow(unused_variables, unused_assignments)] fn main() { - let my_option: Option<&str> = None; - // Assume that you don't know the value of `my_option`. - // In the case of `Some`, we want to print its value. + let my_option: Option<()> = None; if my_option.is_none() { - println!("{}", my_option.unwrap()); + println!("{:?}", my_option.unwrap()); } let my_arr = &[ diff --git a/exercises/quizzes/quiz1.rs b/exercises/quizzes/quiz1.rs index 04fb2aaf..172009b0 100644 --- a/exercises/quizzes/quiz1.rs +++ b/exercises/quizzes/quiz1.rs @@ -16,6 +16,13 @@ fn main() { // You can optionally experiment here. } +fn calculate_price_of_apples(cant:u32)->u32{ + if cant>40{ + return cant; + } + cant*2 +} + // Don't change the tests! #[cfg(test)] mod tests { diff --git a/exercises/quizzes/quiz2.rs b/exercises/quizzes/quiz2.rs index 2cddba90..0451bfd9 100644 --- a/exercises/quizzes/quiz2.rs +++ b/exercises/quizzes/quiz2.rs @@ -27,7 +27,15 @@ 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 { + input.into_iter().map(|(s, c)| { + match c { + Command::Uppercase => s.to_uppercase(), + Command::Trim => s.trim().to_string(), + Command::Append(size) => format!("{}{}", s, "bar".repeat(size)), + } + }).collect() + } } fn main() { @@ -37,12 +45,12 @@ fn main() { #[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] fn it_works() { - let input = vec![ + let input: Vec<(String, Command)> = vec![ ("hello".to_string(), Command::Uppercase), (" all roads lead to rome! ".to_string(), Command::Trim), ("foo".to_string(), Command::Append(1)),