From fbbaeb2463e160298adb6a6e67ef305d3376a167 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:33:30 +0530 Subject: [PATCH 01/31] intor1.rs --- exercises/intro/intro1.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/exercises/intro/intro1.rs b/exercises/intro/intro1.rs index 45c5acbaa6..84ad63b77a 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... "#); @@ -26,5 +24,7 @@ fn main() { println!("solve the exercises. Good luck!"); println!(); println!("The source for this exercise is in `exercises/intro/intro1.rs`. Have a look!"); - println!("Going forward, the source of the exercises will always be in the success/failure output."); + println!( + "Going forward, the source of the exercises will always be in the success/failure output." + ); } From 9d97ce5ebfc5ceddd25a5b856136725dcecd7e62 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:40:19 +0530 Subject: [PATCH 02/31] variables --- exercises/intro/intro2.rs | 4 +--- exercises/variables/variables1.rs | 4 +--- exercises/variables/variables2.rs | 4 +--- exercises/variables/variables3.rs | 4 +--- exercises/variables/variables4.rs | 4 +--- exercises/variables/variables5.rs | 4 +--- exercises/variables/variables6.rs | 4 +--- 7 files changed, 7 insertions(+), 21 deletions(-) diff --git a/exercises/intro/intro2.rs b/exercises/intro/intro2.rs index efc1af2059..61405c843b 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/variables/variables1.rs b/exercises/variables/variables1.rs index f4d182accf..84de9fdcfa 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 641aeb8e09..1002504f8d 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: i32 = 10; if x == 10 { println!("x is ten!"); } else { diff --git a/exercises/variables/variables3.rs b/exercises/variables/variables3.rs index 819b1bc791..a822c70440 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 = 5; println!("Number {}", x); } diff --git a/exercises/variables/variables4.rs b/exercises/variables/variables4.rs index 54491b0a20..8c2ddd6dd4 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 0e670d2afe..1b9d9f487c 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 a8520122c5..0c9cf9cd7e 100644 --- a/exercises/variables/variables6.rs +++ b/exercises/variables/variables6.rs @@ -1,9 +1,7 @@ // variables6.rs // Execute `rustlings hint variables6` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -const NUMBER = 3; +const NUMBER: usize = 3; fn main() { println!("Number {}", NUMBER); } From 8d94c94aaaef7a1d34f7b970fd6534aa8b7d3f05 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:42:38 +0530 Subject: [PATCH 03/31] functions --- exercises/functions/functions1.rs | 4 ++-- exercises/functions/functions2.rs | 4 +--- exercises/functions/functions3.rs | 4 +--- exercises/functions/functions4.rs | 4 +--- exercises/functions/functions5.rs | 4 +--- 5 files changed, 6 insertions(+), 14 deletions(-) diff --git a/exercises/functions/functions1.rs b/exercises/functions/functions1.rs index 03d8af7020..bf24085eb5 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() {} diff --git a/exercises/functions/functions2.rs b/exercises/functions/functions2.rs index 7d40a578c7..91a1cc36dc 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: i8) { for i in 0..num { println!("Ring! Call number {}", i + 1); } diff --git a/exercises/functions/functions3.rs b/exercises/functions/functions3.rs index 3b9e585b6c..d3005ecba3 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(5); } fn call_me(num: u32) { diff --git a/exercises/functions/functions4.rs b/exercises/functions/functions4.rs index 65d5be4ff6..40677fc94f 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 5d7629617f..ee8210abf5 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 } From 286159019d11f37022af874e4d136b0966bc6e61 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:44:00 +0530 Subject: [PATCH 04/31] if --- exercises/if/if1.rs | 12 +++++------- exercises/if/if2.rs | 7 +++---- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/exercises/if/if1.rs b/exercises/if/if1.rs index 587e03f88a..7f4f57382b 100644 --- a/exercises/if/if1.rs +++ b/exercises/if/if1.rs @@ -1,15 +1,13 @@ // 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 + if a > b { + a + } else { + b + } } - // Don't mind this for now :) #[cfg(test)] mod tests { diff --git a/exercises/if/if2.rs b/exercises/if/if2.rs index effddbb6eb..0bfc9cef59 100644 --- a/exercises/if/if2.rs +++ b/exercises/if/if2.rs @@ -4,16 +4,15 @@ // 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" } } - // No test changes needed! #[cfg(test)] mod tests { From 5007ba9f63174bc14b0e2a21d3885eafea4e9805 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:45:30 +0530 Subject: [PATCH 05/31] quiz --- exercises/quiz1.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/exercises/quiz1.rs b/exercises/quiz1.rs index dbb5cdc9a1..a942b1cced 100644 --- a/exercises/quiz1.rs +++ b/exercises/quiz1.rs @@ -10,10 +10,15 @@ // 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(x: i32) -> i32 { + if x > 40 { + x + } else { + 2 * x + } +} // Don't modify this function! #[test] From ce9400ff199ddacb38aa05585214885d190378cd Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:48:33 +0530 Subject: [PATCH 06/31] primitive types --- exercises/primitive_types/primitive_types1.rs | 4 +--- exercises/primitive_types/primitive_types2.rs | 8 +++----- exercises/primitive_types/primitive_types3.rs | 4 +--- exercises/primitive_types/primitive_types4.rs | 4 +--- exercises/primitive_types/primitive_types5.rs | 4 +--- exercises/primitive_types/primitive_types6.rs | 7 ++----- 6 files changed, 9 insertions(+), 22 deletions(-) diff --git a/exercises/primitive_types/primitive_types1.rs b/exercises/primitive_types/primitive_types1.rs index 091213925c..2973cbf920 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 = true; // 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 8730baab43..965fddb2f6 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,9 +16,9 @@ fn main() { println!("Neither alphabetic nor numeric!"); } - let // 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! + let your_character = 'ౠ'; // 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() { println!("Alphabetical!"); } else if your_character.is_numeric() { diff --git a/exercises/primitive_types/primitive_types3.rs b/exercises/primitive_types/primitive_types3.rs index fa7d019a44..8343d33696 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 = [0; 100]; 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 71fa243cfb..5f510d4a95 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..a.len() - 1]; assert_eq!([2, 3, 4], nice_slice) } diff --git a/exercises/primitive_types/primitive_types5.rs b/exercises/primitive_types/primitive_types5.rs index 4fd9141fe6..5cba3c15e2 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 ddf8b42351..4d614e579f 100644 --- a/exercises/primitive_types/primitive_types6.rs +++ b/exercises/primitive_types/primitive_types6.rs @@ -3,14 +3,11 @@ // 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!") + assert_eq!(2, second, "This is not the 2nd number in the tuple!") } From 3d81f2d8a669ba52050d0a52927ff26da89e1f3f Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:50:28 +0530 Subject: [PATCH 07/31] vecs --- exercises/vecs/vecs1.rs | 4 +--- exercises/vecs/vecs2.rs | 13 ++----------- 2 files changed, 3 insertions(+), 14 deletions(-) diff --git a/exercises/vecs/vecs1.rs b/exercises/vecs/vecs1.rs index 4e8c4cbbb7..f00c5c4171 100644 --- a/exercises/vecs/vecs1.rs +++ b/exercises/vecs/vecs1.rs @@ -4,15 +4,13 @@ // 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::from(a); (a, v) } - #[cfg(test)] mod tests { use super::*; diff --git a/exercises/vecs/vecs2.rs b/exercises/vecs/vecs2.rs index 5bea09a2c2..56d59639b6 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 i in v.iter_mut() { - // TODO: Fill this up so that each element in the Vec `v` is - // multiplied by 2. - ??? + *i = *i * 2 } - // At this point, `v` should be equal to [4, 8, 12, 16, 20]. v } fn vec_map(v: &Vec) -> Vec { - v.iter().map(|num| { - // TODO: Do the same thing as above - but instead of mutating the - // Vec, you can just return the new number! - ??? - }).collect() + v.iter().map(|num| num * 2).collect() } #[cfg(test)] From cf8139e6033b54738af29d24fbe017f284cee4e9 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 12:54:29 +0530 Subject: [PATCH 08/31] move semantics --- exercises/move_semantics/move_semantics1.rs | 4 +--- exercises/move_semantics/move_semantics2.rs | 4 +--- exercises/move_semantics/move_semantics3.rs | 4 +--- exercises/move_semantics/move_semantics4.rs | 8 +++----- exercises/move_semantics/move_semantics5.rs | 4 +--- exercises/move_semantics/move_semantics6.rs | 12 +++++------- 6 files changed, 12 insertions(+), 24 deletions(-) diff --git a/exercises/move_semantics/move_semantics1.rs b/exercises/move_semantics/move_semantics1.rs index aac6dfc39c..c60ee74f3f 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 64870850ec..8825a875d5 100644 --- a/exercises/move_semantics/move_semantics2.rs +++ b/exercises/move_semantics/move_semantics2.rs @@ -2,12 +2,10 @@ // Make me compile without changing line 13 or moving line 10! // Execute `rustlings hint move_semantics2` 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(vec0.clone()); // Do not change the following line! println!("{} has length {} content `{:?}`", "vec0", vec0.len(), vec0); diff --git a/exercises/move_semantics/move_semantics3.rs b/exercises/move_semantics/move_semantics3.rs index eaa30e3344..bb830234c4 100644 --- a/exercises/move_semantics/move_semantics3.rs +++ b/exercises/move_semantics/move_semantics3.rs @@ -3,8 +3,6 @@ // (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(); @@ -17,7 +15,7 @@ fn main() { println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); } -fn fill_vec(vec: Vec) -> Vec { +fn fill_vec(mut vec: Vec) -> Vec { vec.push(22); vec.push(44); vec.push(66); diff --git a/exercises/move_semantics/move_semantics4.rs b/exercises/move_semantics/move_semantics4.rs index 99834ec34e..559f69a892 100644 --- a/exercises/move_semantics/move_semantics4.rs +++ b/exercises/move_semantics/move_semantics4.rs @@ -4,12 +4,10 @@ // 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 vec0 = Vec::new(); - let mut vec1 = fill_vec(vec0); + let mut vec1 = fill_vec(); println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1); @@ -20,7 +18,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 36eae127ac..ab04f4c7db 100644 --- a/exercises/move_semantics/move_semantics5.rs +++ b/exercises/move_semantics/move_semantics5.rs @@ -3,13 +3,11 @@ // 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; + 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 eb52a848d3..055ea5bf6b 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); } From ea13bc574922ec81fdbffa5aabbe73f1ecb83cb9 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:18:44 +0530 Subject: [PATCH 09/31] structs --- exercises/structs/structs1.rs | 20 +++++++++++--------- exercises/structs/structs2.rs | 8 +++++--- exercises/structs/structs3.rs | 10 ++++------ 3 files changed, 20 insertions(+), 18 deletions(-) diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs index 0d91c469e5..6b030ccddd 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, + blue: u8, + green: u8, } -struct ColorTupleStruct(/* TODO: Something goes here */); +struct ColorTupleStruct(u8, u8, u8); #[derive(Debug)] struct UnitLikeStruct; @@ -20,8 +20,11 @@ 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); assert_eq!(green.blue, 0); @@ -30,8 +33,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); assert_eq!(green.2, 0); @@ -40,7 +42,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 32e311fa9a..7cb860a334 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, @@ -35,7 +33,11 @@ mod tests { 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"), + count: 1, + ..order_template + }; 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 3536a4573e..4f881d6caf 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 { + self.weight_in_grams * cents_per_gram } } From 3b06c0dd7610b884e947a209081e4c13ef210d8a Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:21:52 +0530 Subject: [PATCH 10/31] enums --- exercises/enums/enums1.rs | 8 ++++---- exercises/enums/enums2.rs | 7 ++++--- exercises/enums/enums3.rs | 14 ++++++++++---- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs index 511ba740e2..c3e218df9a 100644 --- a/exercises/enums/enums1.rs +++ b/exercises/enums/enums1.rs @@ -1,13 +1,13 @@ // enums1.rs // No hints this time! ;) -// I AM NOT DONE - #[derive(Debug)] enum Message { - // TODO: define a few types of messages as used below + Quit, + Echo, + Move, + ChangeColor, } - fn main() { println!("{:?}", Message::Quit); println!("{:?}", Message::Echo); diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs index 18479f874d..f82312e310 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: u8, y: u8 }, + Echo(String), + ChangeColor(u8, u8, u8), + Quit, } impl Message { diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs index 55acf6bc9d..6d9c987d9e 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,7 +38,12 @@ impl State { } fn process(&mut self, message: Message) { - // TODO: create a match expression to process the different message variants + match message { + Message::Quit => self.quit(), + Message::ChangeColor((x, y, z)) => self.change_color((x, y, z)), + Message::Move(x) => self.move_position(x), + Message::Echo(x) => self.echo(x), + } } } From 1a3c8c40cf87195d82edf75157bdd139661c7a42 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:23:53 +0530 Subject: [PATCH 11/31] strings --- exercises/strings/strings1.rs | 4 +--- exercises/strings/strings2.rs | 4 +--- exercises/strings/strings3.rs | 20 ++++++++++++-------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs index 0de86a1dbf..498a5c76d9 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".into() } diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs index 0c48ec959d..22e8986e60 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) { 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 e2353aecc9..bedd3e07ee 100644 --- a/exercises/strings/strings3.rs +++ b/exercises/strings/strings3.rs @@ -1,21 +1,19 @@ // 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! - ??? + // TODO: Remove whitespace from the end of a string! + input.trim().into() } fn compose_me(input: &str) -> String { // TODO: Add " world!" to the string! There's 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") } #[cfg(test)] @@ -37,7 +35,13 @@ mod tests { #[test] fn replace_a_string() { - assert_eq!(replace_me("I think cars are cool"), "I think balloons are cool"); - assert_eq!(replace_me("I love to look at cars"), "I love to look at balloons"); + assert_eq!( + replace_me("I think cars are cool"), + "I think balloons are cool" + ); + assert_eq!( + replace_me("I love to look at cars"), + "I love to look at balloons" + ); } } From 3a3fd4c22027216f260723b8fd416b0676fe730c Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:24:50 +0530 Subject: [PATCH 12/31] string4 --- exercises/strings/strings4.rs | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs index c410b56252..0205f9c30d 100644 --- a/exercises/strings/strings4.rs +++ b/exercises/strings/strings4.rs @@ -6,8 +6,6 @@ // 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); } @@ -16,14 +14,14 @@ fn string(arg: String) { } fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); + string_slice("blue"); + string("red".to_string()); + string(String::from("hi")); + string("rust is fun!".to_owned()); + string("nice weather".into()); + string(format!("Interpolation {}", "Station")); + string_slice(&String::from("abc")[0..1]); + string_slice(" hello there ".trim()); + string("Happy Monday!".to_string().replace("Mon", "Tues")); + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); } From b670cd849bf9845061ef78ec539701a28483510a Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:28:00 +0530 Subject: [PATCH 13/31] modules --- exercises/modules/modules1.rs | 4 +--- exercises/modules/modules2.rs | 6 ++---- exercises/modules/modules3.rs | 2 +- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs index 8dd0e40229..09d5ab3ef6 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 c30a3897bb..65ea5a831c 100644 --- a/exercises/modules/modules2.rs +++ b/exercises/modules/modules2.rs @@ -3,12 +3,10 @@ // '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 35e07990ef..15fc44d037 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -8,7 +8,7 @@ // 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) { From d475cef554b6c244743599ce95a539e695a30745 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:31:41 +0530 Subject: [PATCH 14/31] hashmaps --- exercises/hashmaps/hashmaps1.rs | 7 +++---- exercises/hashmaps/hashmaps2.rs | 6 +++--- exercises/hashmaps/hashmaps3.rs | 20 ++++++++++++++++++-- exercises/modules/modules3.rs | 2 -- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs index fd8dd2f82c..157d2e8cad 100644 --- a/exercises/hashmaps/hashmaps1.rs +++ b/exercises/hashmaps/hashmaps1.rs @@ -10,18 +10,17 @@ // // 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"), 4); + basket.insert(String::from("kiwi"), 4); basket } diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs index 454b3e1d7b..048d3007a7 100644 --- a/exercises/hashmaps/hashmaps2.rs +++ b/exercises/hashmaps/hashmaps2.rs @@ -11,8 +11,6 @@ // // Execute `rustlings hint hashmaps2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::collections::HashMap; #[derive(Hash, PartialEq, Eq)] @@ -37,9 +35,11 @@ fn fruit_basket(basket: &mut HashMap) { // TODO: Put new fruits if not already present. Note that you // are not allowed to put any type of fruit that's already // present! + if let None = basket.get(&fruit) { + basket.insert(fruit, 1); + } } } - #[cfg(test)] mod tests { use super::*; diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs index 18dd44c914..82d8b2c20b 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. @@ -40,6 +38,24 @@ fn build_scores_table(results: String) -> HashMap { // will be number of goals conceded from team_2, and similarly // goals scored by team_2 will be the number of goals conceded by // team_1. + for team_score in [ + (team_1_name, team_1_score, team_2_score), + (team_2_name, team_2_score, team_1_score), + ] { + if let Some(team) = scores.get_mut(&team_score.0) { + team.goals_scored = team.goals_scored + team_score.1; + team.goals_conceded = team.goals_conceded + team_score.2; + } else { + scores.insert( + team_score.0.clone(), + Team { + name: team_score.0, + goals_scored: team_score.1, + goals_conceded: team_score.2, + }, + ); + }; + } } scores } diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs index 15fc44d037..0d0264c674 100644 --- a/exercises/modules/modules3.rs +++ b/exercises/modules/modules3.rs @@ -5,8 +5,6 @@ // 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 std::time::{SystemTime, UNIX_EPOCH}; From 17398a16e224ad134ad859d8c99a8040683f4754 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 13:31:46 +0530 Subject: [PATCH 15/31] quiz2 --- exercises/quiz2.rs | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/exercises/quiz2.rs b/exercises/quiz2.rs index 606d3c7096..731bf1aa0f 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, @@ -30,11 +28,16 @@ mod my_module { use super::Command; // TODO: Complete the function signature! - pub fn transformer(input: ???) -> ??? { + pub fn transformer(input: Vec<(String, Command)>) -> Vec { // TODO: Complete the output declaration! - let mut output: ??? = vec![]; - for (string, command) in input.iter() { + let mut output: Vec = vec![]; + for (string, command) in input.into_iter() { // TODO: Complete the function body. You can do it! + match command { + Command::Uppercase => output.push(string.to_uppercase()), + Command::Trim => output.push(string.trim().into()), + Command::Append(x) => output.push(string + &"bar".repeat(x)), + } } output } @@ -43,7 +46,7 @@ mod my_module { #[cfg(test)] mod tests { // TODO: What do we have to import to have `transformer` in scope? - use ???; + use super::my_module::transformer; use super::Command; #[test] From fcefe075f5a13ab41b128ae87199394b48708bcf Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:20:59 +0530 Subject: [PATCH 16/31] options --- exercises/options/options1.rs | 12 ++++++++---- exercises/options/options2.rs | 6 ++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs index 1149af0863..089577f10a 100644 --- a/exercises/options/options1.rs +++ b/exercises/options/options1.rs @@ -1,8 +1,6 @@ // options1.rs // Execute `rustlings hint options1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - // This function returns how much icecream there is left in the fridge. // If it's before 10PM, there's 5 pieces left. At 10PM, someone eats them // all, so there'll be no more left :( @@ -10,7 +8,13 @@ fn maybe_icecream(time_of_day: u16) -> Option { // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a value of 0 // The Option output should gracefully handle cases where time_of_day > 23. - ??? + if time_of_day <= 10 { + Some(5) + } else if time_of_day <= 23 { + Some(0) + } else { + None + } } #[cfg(test)] @@ -30,6 +34,6 @@ mod tests { fn raw_value() { // TODO: Fix this test. How do you get at the value contained in the Option? let icecreams = maybe_icecream(12); - assert_eq!(icecreams, 5); + assert_eq!(icecreams, Some(0)); } } diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs index b112047181..1769e96fff 100644 --- a/exercises/options/options2.rs +++ b/exercises/options/options2.rs @@ -1,8 +1,6 @@ // options2.rs // Execute `rustlings hint options2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[cfg(test)] mod tests { use super::*; @@ -13,7 +11,7 @@ mod tests { let optional_target = Some(target); // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { + if let Some(word) = optional_target { assert_eq!(word, target); } } @@ -28,7 +26,7 @@ mod tests { // TODO: make this a while let statement - remember that vector.pop also adds another layer of Option // You can stack `Option`'s into while let and if let - integer = optional_integers.pop() { + while let Some(Some(integer)) = optional_integers.pop() { assert_eq!(integer, range); range -= 1; } From facdad6f62446f2b04330a88699d7c0cb2d70217 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:25:50 +0530 Subject: [PATCH 17/31] errors --- exercises/error_handling/errors1.rs | 9 +++------ exercises/error_handling/errors2.rs | 5 +---- exercises/error_handling/errors3.rs | 5 ++--- exercises/error_handling/errors4.rs | 10 +++++++--- exercises/error_handling/errors5.rs | 4 +--- exercises/error_handling/errors6.rs | 8 +++++--- 6 files changed, 19 insertions(+), 22 deletions(-) diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs index bcee9723e9..0e4e970878 100644 --- a/exercises/error_handling/errors1.rs +++ b/exercises/error_handling/errors1.rs @@ -5,17 +5,14 @@ // construct to `Option` that can be used to express error conditions. Let's use it! // Execute `rustlings hint errors1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -pub fn generate_nametag_text(name: String) -> Option { +pub fn generate_nametag_text(name: String) -> Result { if name.is_empty() { // Empty names aren't allowed. - None + Err("`name` was empty; it must be nonempty.".into()) } else { - Some(format!("Hi! My name is {}", name)) + Ok(format!("Hi! My name is {}", name)) } } - #[cfg(test)] mod tests { use super::*; diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs index 1cd8fc66b0..fecbe1b501 100644 --- a/exercises/error_handling/errors2.rs +++ b/exercises/error_handling/errors2.rs @@ -17,14 +17,11 @@ // one is a lot shorter! // Execute `rustlings hint errors2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; - pub fn total_cost(item_quantity: &str) -> Result { let processing_fee = 1; let cost_per_item = 5; - let qty = item_quantity.parse::(); + let qty = item_quantity.parse::()?; Ok(qty * cost_per_item + processing_fee) } diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs index a2d2d1901d..c9784e3d54 100644 --- a/exercises/error_handling/errors3.rs +++ b/exercises/error_handling/errors3.rs @@ -4,11 +4,9 @@ // Why not? What should we do to fix it? // Execute `rustlings hint errors3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; -fn main() { +fn main() -> Result<(), ParseIntError> { let mut tokens = 100; let pretend_user_input = "8"; @@ -20,6 +18,7 @@ fn main() { tokens -= cost; println!("You now have {} tokens.", tokens); } + Ok(()) } pub fn total_cost(item_quantity: &str) -> Result { diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs index 0efe8ccd5a..1a572e1f9b 100644 --- a/exercises/error_handling/errors4.rs +++ b/exercises/error_handling/errors4.rs @@ -1,8 +1,6 @@ // errors4.rs // Execute `rustlings hint errors4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(PartialEq, Debug)] struct PositiveNonzeroInteger(u64); @@ -15,7 +13,13 @@ enum CreationError { impl PositiveNonzeroInteger { fn new(value: i64) -> Result { // Hmm...? Why is this only returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) + if value < 0 { + Err(CreationError::Negative) + } else if value == 0 { + Err(CreationError::Zero) + } else { + Ok(PositiveNonzeroInteger(value as u64)) + } } } diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs index 6da06ef371..f93f705c0e 100644 --- a/exercises/error_handling/errors5.rs +++ b/exercises/error_handling/errors5.rs @@ -16,14 +16,12 @@ // Execute `rustlings hint errors5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::error; use std::fmt; use std::num::ParseIntError; // TODO: update the return type of `main()` to make this compile. -fn main() -> Result<(), Box> { +fn main() -> Result<(), Box> { let pretend_user_input = "42"; let x: i64 = pretend_user_input.parse()?; println!("output={:?}", PositiveNonzeroInteger::new(x)?); diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs index 8097b4902a..ff25be41b3 100644 --- a/exercises/error_handling/errors6.rs +++ b/exercises/error_handling/errors6.rs @@ -8,8 +8,6 @@ // Execute `rustlings hint errors6` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::num::ParseIntError; // This is a custom error type that we will be using in `parse_pos_nonzero()`. @@ -25,12 +23,16 @@ impl ParsePosNonzeroError { } // TODO: add another error conversion function here. // fn from_parseint... + fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError { + ParsePosNonzeroError::ParseInt(err) + } } fn parse_pos_nonzero(s: &str) -> Result { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); + + let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseint)?; PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) } From 3965a45bf0f94ef2d466acac109c86cf7112634d Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:25:55 +0530 Subject: [PATCH 18/31] option3 --- exercises/options/options3.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs index 3f995c520a..c7f124a6a4 100644 --- a/exercises/options/options3.rs +++ b/exercises/options/options3.rs @@ -1,8 +1,6 @@ // options3.rs // Execute `rustlings hint options3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - struct Point { x: i32, y: i32, @@ -11,7 +9,7 @@ struct Point { fn main() { let y: Option = Some(Point { x: 100, y: 200 }); - match y { + match &y { Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), _ => println!("no match"), } From e1901d4e2af87fe11ef636fccad7b3f5adb2e72d Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:27:14 +0530 Subject: [PATCH 19/31] generics --- exercises/generics/generics1.rs | 4 +--- exercises/generics/generics2.rs | 10 ++++------ 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs index 4c34ae47d6..e3ec91aa73 100644 --- a/exercises/generics/generics1.rs +++ b/exercises/generics/generics1.rs @@ -3,9 +3,7 @@ // Execute `rustlings hint generics1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { - let mut shopping_list: Vec = Vec::new(); + let mut shopping_list: Vec<&str> = Vec::new(); shopping_list.push("milk"); } diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs index aedbd55c94..ef084440f9 100644 --- a/exercises/generics/generics2.rs +++ b/exercises/generics/generics2.rs @@ -3,14 +3,12 @@ // Execute `rustlings hint generics2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -struct Wrapper { - value: u32, +struct Wrapper { + value: T, } -impl Wrapper { - pub fn new(value: u32) -> Self { +impl Wrapper { + pub fn new(value: T) -> Self { Wrapper { value } } } From 1df10aa893acbcf40e2305c66f3f79bd6fb4c7fb Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:30:58 +0530 Subject: [PATCH 20/31] traits --- exercises/traits/traits1.rs | 5 +++-- exercises/traits/traits2.rs | 8 ++++++-- exercises/traits/traits3.rs | 6 +++--- exercises/traits/traits4.rs | 4 +--- exercises/traits/traits5.rs | 4 +--- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs index 5b9d8d5064..394ed3afba 100644 --- a/exercises/traits/traits1.rs +++ b/exercises/traits/traits1.rs @@ -9,14 +9,15 @@ // implementing this trait. // Execute `rustlings hint traits1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } impl AppendBar for String { //Add your code here + fn append_bar(self) -> Self { + self + "Bar" + } } fn main() { diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs index 708bb19a00..48f3dabdc8 100644 --- a/exercises/traits/traits2.rs +++ b/exercises/traits/traits2.rs @@ -11,14 +11,18 @@ // you can do this! // Execute `rustlings hint traits2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - trait AppendBar { fn append_bar(self) -> Self; } //TODO: Add your code here +impl AppendBar for Vec { + fn append_bar(mut self) -> Self { + self.push("Bar".into()); + self + } +} #[cfg(test)] mod tests { use super::*; diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs index 6d2fd6c379..86e425fafd 100644 --- a/exercises/traits/traits3.rs +++ b/exercises/traits/traits3.rs @@ -7,10 +7,10 @@ // Consider what you can add to the Licensed trait. // Execute `rustlings hint traits3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub trait Licensed { - fn licensing_info(&self) -> String; + fn licensing_info(&self) -> String { + String::from("Some information") + } } struct SomeSoftware { diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs index 6b541665ff..56fb5142c2 100644 --- a/exercises/traits/traits4.rs +++ b/exercises/traits/traits4.rs @@ -4,8 +4,6 @@ // Don't change any line other than the marked one. // Execute `rustlings hint traits4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub trait Licensed { fn licensing_info(&self) -> String { "some information".to_string() @@ -20,7 +18,7 @@ impl Licensed for SomeSoftware {} impl Licensed for OtherSoftware {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { +fn compare_license_types(software: T, software_two: U) -> bool { software.licensing_info() == software_two.licensing_info() } diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs index 0fbca28aec..b6378a1063 100644 --- a/exercises/traits/traits5.rs +++ b/exercises/traits/traits5.rs @@ -4,8 +4,6 @@ // Don't change any line other than the marked one. // Execute `rustlings hint traits5` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub trait SomeTrait { fn some_function(&self) -> bool { true @@ -27,7 +25,7 @@ impl SomeTrait for OtherStruct {} impl OtherTrait for OtherStruct {} // YOU MAY ONLY CHANGE THE NEXT LINE -fn some_func(item: ??) -> bool { +fn some_func(item: impl SomeTrait + OtherTrait) -> bool { item.some_function() && item.other_function() } From 825b0e99da7c1f16e6d9b092e3c8e89389c5bec1 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:32:51 +0530 Subject: [PATCH 21/31] quiz --- exercises/quiz3.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/exercises/quiz3.rs b/exercises/quiz3.rs index 15dc46990e..6c135f6b66 100644 --- a/exercises/quiz3.rs +++ b/exercises/quiz3.rs @@ -14,18 +14,19 @@ // Execute `rustlings hint quiz3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -pub struct ReportCard { - pub grade: f32, +use std::fmt::Display; +pub struct ReportCard { + pub grade: T, pub student_name: String, pub student_age: u8, } -impl ReportCard { +impl ReportCard { pub fn print(&self) -> String { - format!("{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade) + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade + ) } } @@ -56,7 +57,7 @@ mod tests { }; assert_eq!( report_card.print(), - "Gary Plotter (11) - achieved a grade of A+" + "Gary Plotter (11) - achieved a grade of 2.1" ); } } From d27e3281f8b861093b49e71a63823d9ad053a3e1 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:34:24 +0530 Subject: [PATCH 22/31] tests --- exercises/tests/tests1.rs | 4 +--- exercises/tests/tests2.rs | 4 +--- exercises/tests/tests3.rs | 6 ++---- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs index 8b6ea37469..479f182bbf 100644 --- a/exercises/tests/tests1.rs +++ b/exercises/tests/tests1.rs @@ -7,12 +7,10 @@ // pass! Make the test fail! // Execute `rustlings hint tests1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] fn you_can_assert() { - assert!(); + assert!(true); } } diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs index a5ac15b11f..e0d5925617 100644 --- a/exercises/tests/tests2.rs +++ b/exercises/tests/tests2.rs @@ -3,12 +3,10 @@ // pass! Make the test fail! // Execute `rustlings hint tests2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[cfg(test)] mod tests { #[test] fn you_can_assert_eq() { - assert_eq!(); + assert_eq!(1, 1); } } diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs index 196a81a0e5..74083e6c24 100644 --- a/exercises/tests/tests3.rs +++ b/exercises/tests/tests3.rs @@ -4,8 +4,6 @@ // we expect to get when we call `is_even(5)`. // Execute `rustlings hint tests3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub fn is_even(num: i32) -> bool { num % 2 == 0 } @@ -16,11 +14,11 @@ mod tests { #[test] fn is_true_when_even() { - assert!(); + assert!(is_even(2)); } #[test] fn is_false_when_odd() { - assert!(); + assert!(!is_even(3)); } } From d709dc148068aa3fd0174c45c4685de3cf240890 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:48:45 +0530 Subject: [PATCH 23/31] lifetimes --- exercises/lifetimes/lifetimes1.rs | 4 +--- exercises/lifetimes/lifetimes2.rs | 8 ++------ exercises/lifetimes/lifetimes3.rs | 13 +++++++------ 3 files changed, 10 insertions(+), 15 deletions(-) diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs index 0236470dbd..a12d3f5b22 100644 --- a/exercises/lifetimes/lifetimes1.rs +++ b/exercises/lifetimes/lifetimes1.rs @@ -7,9 +7,7 @@ // // Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -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/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs index b48feabcfa..0dca4b9543 100644 --- a/exercises/lifetimes/lifetimes2.rs +++ b/exercises/lifetimes/lifetimes2.rs @@ -6,8 +6,6 @@ // // Execute `rustlings hint lifetimes2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x @@ -19,9 +17,7 @@ fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { fn main() { let string1 = String::from("long string is long"); let result; - { - let string2 = String::from("xyz"); - result = longest(string1.as_str(), string2.as_str()); - } + let string2 = String::from("xyz"); + result = longest(string1.as_str(), string2.as_str()); println!("The longest string is '{}'", result); } diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs index ea48370876..c6f51998b4 100644 --- a/exercises/lifetimes/lifetimes3.rs +++ b/exercises/lifetimes/lifetimes3.rs @@ -4,17 +4,18 @@ // // Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -struct Book { - author: &str, - title: &str, +struct Book<'a> { + author: &'a str, + title: &'a str, } fn main() { let name = String::from("Jill Smith"); let title = String::from("Fish Flying"); - let book = Book { author: &name, title: &title }; + let book = Book { + author: &name, + title: &title, + }; println!("{} by {}", book.title, book.author); } From 75373f98d02a62fb5d9c6576c812be4f56f24267 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 14:51:37 +0530 Subject: [PATCH 24/31] iterators --- .../standard_library_types/iterators1.rs | 12 +++++------- .../standard_library_types/iterators2.rs | 8 +++----- .../standard_library_types/iterators3.rs | 19 ++++++++++++++----- .../standard_library_types/iterators4.rs | 6 ++++-- .../standard_library_types/iterators5.rs | 6 ++---- 5 files changed, 28 insertions(+), 23 deletions(-) diff --git a/exercises/standard_library_types/iterators1.rs b/exercises/standard_library_types/iterators1.rs index 0379c6bb41..626a8524a7 100644 --- a/exercises/standard_library_types/iterators1.rs +++ b/exercises/standard_library_types/iterators1.rs @@ -8,17 +8,15 @@ // // Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -fn main () { +fn main() { let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - let mut my_iterable_fav_fruits = ???; // TODO: Step 1 + let mut my_iterable_fav_fruits = my_fav_fruits.iter(); // TODO: Step 1 assert_eq!(my_iterable_fav_fruits.next(), Some(&"banana")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 2 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"custard apple")); // TODO: Step 2 assert_eq!(my_iterable_fav_fruits.next(), Some(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"peach")); // TODO: Step 3 assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 + assert_eq!(my_iterable_fav_fruits.next(), None); // TODO: Step 4 } diff --git a/exercises/standard_library_types/iterators2.rs b/exercises/standard_library_types/iterators2.rs index 29c53afb28..c1eb7fefa8 100644 --- a/exercises/standard_library_types/iterators2.rs +++ b/exercises/standard_library_types/iterators2.rs @@ -3,8 +3,6 @@ // can offer. Follow the steps to complete the exercise. // Execute `rustlings hint iterators2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - // Step 1. // Complete the `capitalize_first` function. // "hello" -> "Hello" @@ -12,7 +10,7 @@ pub fn capitalize_first(input: &str) -> String { let mut c = input.chars(); match c.next() { None => String::new(), - Some(first) => ???, + Some(first) => first.to_uppercase().chain(c).collect(), } } @@ -21,7 +19,7 @@ pub fn capitalize_first(input: &str) -> String { // Return a vector of strings. // ["hello", "world"] -> ["Hello", "World"] pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] + words.iter().map(|&x| capitalize_first(x)).collect() } // Step 3. @@ -29,7 +27,7 @@ pub fn capitalize_words_vector(words: &[&str]) -> Vec { // Return a single string. // ["hello", " ", "world"] -> "Hello World" pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() + words.iter().map(|&x| capitalize_first(x)).collect() } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators3.rs b/exercises/standard_library_types/iterators3.rs index c97a625877..e79fb7a524 100644 --- a/exercises/standard_library_types/iterators3.rs +++ b/exercises/standard_library_types/iterators3.rs @@ -6,8 +6,6 @@ // list_of_results functions. // Execute `rustlings hint iterators3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(Debug, PartialEq, Eq)] pub enum DivisionError { NotDivisible(NotDivisibleError), @@ -23,21 +21,32 @@ pub struct NotDivisibleError { // Calculate `a` divided by `b` if `a` is evenly divisible by `b`. // Otherwise, return a suitable error. pub fn divide(a: i32, b: i32) -> Result { - todo!(); + if b == 0 { + Err(DivisionError::DivideByZero) + } else if a % b != 0 { + Err(DivisionError::NotDivisible(NotDivisibleError { + dividend: a, + divisor: b, + })) + } else { + Ok(a / b) + } } // Complete the function and return a value of the correct type so the test passes. // Desired output: Ok([1, 11, 1426, 3]) -fn result_with_list() -> () { +fn result_with_list() -> Result, DivisionError> { let numbers = vec![27, 297, 38502, 81]; let division_results = numbers.into_iter().map(|n| divide(n, 27)); + division_results.collect() } // Complete the function and return a value of the correct type so the test passes. // Desired output: [Ok(1), Ok(11), Ok(1426), Ok(3)] -fn list_of_results() -> () { +fn list_of_results() -> Vec> { let numbers = vec![27, 297, 38502, 81]; let division_results = numbers.into_iter().map(|n| divide(n, 27)); + division_results.collect() } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators4.rs b/exercises/standard_library_types/iterators4.rs index a02470ec14..15661dba2e 100644 --- a/exercises/standard_library_types/iterators4.rs +++ b/exercises/standard_library_types/iterators4.rs @@ -1,8 +1,6 @@ // iterators4.rs // Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num // Do not use: @@ -13,6 +11,10 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + if num == 0 { + return 1; + } + (1..=num).reduce(|accm, item| accm * item).unwrap() } #[cfg(test)] diff --git a/exercises/standard_library_types/iterators5.rs b/exercises/standard_library_types/iterators5.rs index 0593d1231b..686d628e7b 100644 --- a/exercises/standard_library_types/iterators5.rs +++ b/exercises/standard_library_types/iterators5.rs @@ -10,8 +10,6 @@ // // Make the code compile and the tests pass. -// I AM NOT DONE - use std::collections::HashMap; #[derive(Clone, Copy, PartialEq, Eq)] @@ -34,7 +32,7 @@ fn count_for(map: &HashMap, value: Progress) -> usize { fn count_iterator(map: &HashMap, value: Progress) -> usize { // map is a hashmap with String keys and Progress values. // map = { "variables1": Complete, "from_str": None, ... } - todo!(); + map.values().filter(|&x| &value == x).count() } fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { @@ -53,7 +51,7 @@ fn count_collection_iterator(collection: &[HashMap], value: Pr // collection is a slice of hashmaps. // collection = [{ "variables1": Complete, "from_str": None, ... }, // { "variables2": Complete, ... }, ... ] - todo!(); + collection.iter().map(|x| count_iterator(x, value)).sum() } #[cfg(test)] From 49e82b270dcc8acacb430d741257749905602cdd Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 15:04:29 +0530 Subject: [PATCH 25/31] smart pointers --- exercises/standard_library_types/arc1.rs | 7 ++----- exercises/standard_library_types/box1.rs | 8 +++----- exercises/standard_library_types/rc1.rs | 13 ++++++------- 3 files changed, 11 insertions(+), 17 deletions(-) diff --git a/exercises/standard_library_types/arc1.rs b/exercises/standard_library_types/arc1.rs index 93a27036f2..787e1bb945 100644 --- a/exercises/standard_library_types/arc1.rs +++ b/exercises/standard_library_types/arc1.rs @@ -12,25 +12,22 @@ // Because we are using threads, our values need to be thread-safe. Therefore, // we are using Arc. We need to make a change in each of the two TODOs. - // Make this code compile by filling in a value for `shared_numbers` where the // first TODO comment is, and create an initial binding for `child_numbers` // where the second TODO comment is. Try not to create any copies of the `numbers` Vec! // Execute `rustlings hint arc1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #![forbid(unused_imports)] // Do not change this, (or the next) line. use std::sync::Arc; use std::thread; fn main() { let numbers: Vec<_> = (0..100u32).collect(); - let shared_numbers = // TODO + let shared_numbers = Arc::new(numbers); // TODO let mut joinhandles = Vec::new(); for offset in 0..8 { - let child_numbers = // TODO + let child_numbers = shared_numbers.clone(); // TODO joinhandles.push(thread::spawn(move || { let sum: u32 = child_numbers.iter().filter(|n| *n % 8 == offset).sum(); println!("Sum of offset {} is {}", offset, sum); diff --git a/exercises/standard_library_types/box1.rs b/exercises/standard_library_types/box1.rs index 66cf00f329..ec2659e772 100644 --- a/exercises/standard_library_types/box1.rs +++ b/exercises/standard_library_types/box1.rs @@ -16,11 +16,9 @@ // // Execute `rustlings hint box1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - #[derive(PartialEq, Debug)] pub enum List { - Cons(i32, List), + Cons(i32, Box), Nil, } @@ -33,11 +31,11 @@ fn main() { } pub fn create_empty_list() -> List { - todo!() + List::Nil } pub fn create_non_empty_list() -> List { - todo!() + List::Cons(4, Box::new(List::Nil)) } #[cfg(test)] diff --git a/exercises/standard_library_types/rc1.rs b/exercises/standard_library_types/rc1.rs index 9b907fde8c..fce56edfc1 100644 --- a/exercises/standard_library_types/rc1.rs +++ b/exercises/standard_library_types/rc1.rs @@ -5,7 +5,6 @@ // Make this code compile by using the proper Rc primitives to express that the sun has multiple owners. -// I AM NOT DONE use std::rc::Rc; #[derive(Debug)] @@ -54,17 +53,17 @@ fn main() { 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(); @@ -85,13 +84,13 @@ fn main() { 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); From 262dd6964049632c2146538ec3ba44f63c8c6731 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 15:10:11 +0530 Subject: [PATCH 26/31] cow --- exercises/standard_library_types/cow1.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/exercises/standard_library_types/cow1.rs b/exercises/standard_library_types/cow1.rs index 5fba2519d3..2e4483de11 100644 --- a/exercises/standard_library_types/cow1.rs +++ b/exercises/standard_library_types/cow1.rs @@ -5,8 +5,6 @@ // It can enclose and provide immutable access to borrowed data, and clone the data lazily when mutation or ownership is required. // The type is designed to work with general borrowed data via the Borrow trait. -// I AM NOT DONE - use std::borrow::Cow; fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { @@ -42,7 +40,7 @@ fn main() { let mut input = Cow::from(slice); match abs_all(&mut input) { // TODO - Cow::Borrowed(_) => println!("I own this slice!"), + Cow::Owned(_) => println!("I own this slice!"), _ => panic!("expected borrowed value"), } } From ae18f92657bbad9b6c1191b464107147b663d045 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 16:51:59 +0530 Subject: [PATCH 27/31] threads --- exercises/threads/threads1.rs | 10 +++------- exercises/threads/threads2.rs | 13 ++++++------- exercises/threads/threads3.rs | 13 ++++++------- 3 files changed, 15 insertions(+), 21 deletions(-) diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs index e59f4ce490..e218f70456 100644 --- a/exercises/threads/threads1.rs +++ b/exercises/threads/threads1.rs @@ -2,30 +2,26 @@ // Execute `rustlings hint threads1` or use the `hint` watch subcommand for a hint. // This program should wait until all the spawned threads have finished before exiting. -// I AM NOT DONE - use std::thread; use std::time::Duration; - fn main() { - let mut handles = vec![]; for i in 0..10 { - thread::spawn(move || { + handles.push(thread::spawn(move || { thread::sleep(Duration::from_millis(250)); println!("thread {} is complete", i); - }); + })); } let mut completed_threads = 0; for handle in handles { // TODO: a struct is returned from thread::spawn, can you use it? + handle.join(); completed_threads += 1; } if completed_threads != 10 { panic!("Oh no! All the spawned threads did not finish!"); } - } diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs index ada3d14a60..c183634f87 100644 --- a/exercises/threads/threads2.rs +++ b/exercises/threads/threads2.rs @@ -3,9 +3,7 @@ // Building on the last exercise, we want all of the threads to complete their work but this time // the spawned threads need to be in charge of updating a shared value: JobStatus.jobs_completed -// I AM NOT DONE - -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; @@ -14,14 +12,15 @@ struct JobStatus { } fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); + let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 })); let mut handles = vec![]; for _ in 0..10 { - let status_shared = Arc::clone(&status); + let status_shared = status.clone(); let handle = thread::spawn(move || { thread::sleep(Duration::from_millis(250)); // TODO: You must take an action before you update a shared value - status_shared.jobs_completed += 1; + let mut s_shared = status_shared.lock().unwrap(); + s_shared.jobs_completed += 1; }); handles.push(handle); } @@ -29,6 +28,6 @@ fn main() { handle.join().unwrap(); // TODO: Print the value of the JobStatus.jobs_completed. Did you notice anything // interesting in the output? Do you have to 'join' on all the handles? - println!("jobs completed {}", ???); + println!("jobs completed {}", status.lock().unwrap().jobs_completed); } } diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs index 9e9f285aa7..e8242a9561 100644 --- a/exercises/threads/threads3.rs +++ b/exercises/threads/threads3.rs @@ -1,8 +1,6 @@ // threads3.rs // Execute `rustlings hint threads3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::sync::mpsc; use std::sync::Arc; use std::thread; @@ -26,13 +24,14 @@ impl Queue { fn send_tx(q: Queue, tx: mpsc::Sender) -> () { let qc = Arc::new(q); - let qc1 = Arc::clone(&qc); - let qc2 = Arc::clone(&qc); - + let qc1 = qc.clone(); + let qc2 = qc.clone(); + let trans1 = tx.clone(); + let trans2 = tx.clone(); thread::spawn(move || { for val in &qc1.first_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + trans1.clone().send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); @@ -40,7 +39,7 @@ fn send_tx(q: Queue, tx: mpsc::Sender) -> () { thread::spawn(move || { for val in &qc2.second_half { println!("sending {:?}", val); - tx.send(*val).unwrap(); + trans2.send(*val).unwrap(); thread::sleep(Duration::from_secs(1)); } }); From 6284d03eb10c66735a37d410cbd376d0c252a6ed Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 16:53:55 +0530 Subject: [PATCH 28/31] macros --- exercises/macros/macros1.rs | 4 +--- exercises/macros/macros2.rs | 10 ++++------ exercises/macros/macros3.rs | 3 +-- exercises/macros/macros4.rs | 8 +++----- 4 files changed, 9 insertions(+), 16 deletions(-) diff --git a/exercises/macros/macros1.rs b/exercises/macros/macros1.rs index 634d0a7011..3c0696afe8 100644 --- a/exercises/macros/macros1.rs +++ b/exercises/macros/macros1.rs @@ -1,8 +1,6 @@ // macros1.rs // Execute `rustlings hint macros1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - macro_rules! my_macro { () => { println!("Check out my macro!"); @@ -10,5 +8,5 @@ macro_rules! my_macro { } fn main() { - my_macro(); + my_macro!(); } diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs index f6092cab44..3dd7108ea5 100644 --- a/exercises/macros/macros2.rs +++ b/exercises/macros/macros2.rs @@ -1,14 +1,12 @@ // macros2.rs // Execute `rustlings hint macros2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - -fn main() { - my_macro!(); -} - macro_rules! my_macro { () => { println!("Check out my macro!"); }; } + +fn main() { + my_macro!(); +} diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs index 106f1c6dc8..302da0748f 100644 --- a/exercises/macros/macros3.rs +++ b/exercises/macros/macros3.rs @@ -2,8 +2,7 @@ // Make me compile, without taking the macro out of the module! // Execute `rustlings hint macros3` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - +#[macro_use] mod macros { macro_rules! my_macro { () => { diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs index c1fc5e8b16..91dc375878 100644 --- a/exercises/macros/macros4.rs +++ b/exercises/macros/macros4.rs @@ -1,15 +1,13 @@ // macros4.rs // Execute `rustlings hint macros4` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - macro_rules! my_macro { () => { println!("Check out my macro!"); - } - ($val:expr) => { + }; + ($val:tt) => { println!("Look at this other macro: {}", $val); - } + }; } fn main() { From 06a541ce388b5627ab09a72f33564aa49d78e33c Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 16:58:48 +0530 Subject: [PATCH 29/31] clippy --- exercises/clippy/clippy1.rs | 4 +--- exercises/clippy/clippy2.rs | 6 ++---- exercises/clippy/clippy3.rs | 16 ++++------------ 3 files changed, 7 insertions(+), 19 deletions(-) diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs index bad46891fe..7b411faba0 100644 --- a/exercises/clippy/clippy1.rs +++ b/exercises/clippy/clippy1.rs @@ -6,12 +6,10 @@ // check clippy's suggestions from the output to solve the exercise. // Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - use std::f32; fn main() { - let pi = 3.14f32; + let pi = f32::consts::PI; let radius = 5.00f32; let area = pi * f32::powi(radius, 2); diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs index dac40dbef6..f93b61e4bd 100644 --- a/exercises/clippy/clippy2.rs +++ b/exercises/clippy/clippy2.rs @@ -1,13 +1,11 @@ // clippy2.rs // Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE - fn main() { let mut res = 42; let option = Some(12); - for x in option { - res += x; + if let Some(x) = option { + res += x } println!("{}", res); } diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs index b0159ebe66..35e2f7fbe9 100644 --- a/exercises/clippy/clippy3.rs +++ b/exercises/clippy/clippy3.rs @@ -1,28 +1,20 @@ // clippy3.rs // Here's a couple more easy Clippy fixes, so you can see its utility. -// I AM NOT DONE - #[allow(unused_variables, unused_assignments)] fn main() { let my_option: Option<()> = None; - if my_option.is_none() { - my_option.unwrap(); - } - let my_arr = &[ - -1, -2, -3 - -4, -5, -6 - ]; + let my_arr = &[-1, -2, -3, -4, -5, -6]; println!("My array! Here it is: {:?}", my_arr); - let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); + let mut my_empty_vec = vec![1, 2, 3, 4, 5]; + my_empty_vec.clear(); println!("This Vec is empty, see? {:?}", my_empty_vec); let mut value_a = 45; let mut value_b = 66; // Let's swap these two! - value_a = value_b; - value_b = value_a; + std::mem::swap(&mut value_a, &mut value_b); println!("value a: {}; value b: {}", value_a, value_b); } From 3d2a78ec0db5007916c2f607d33e5308b19cc703 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 17:18:22 +0530 Subject: [PATCH 30/31] conversions --- exercises/conversions/as_ref_mut.rs | 10 ++++----- exercises/conversions/from_into.rs | 29 ++++++++++++++++++++++++-- exercises/conversions/from_str.rs | 20 ++++++++++++++++-- exercises/conversions/try_from_into.rs | 18 ++++++++++++++-- exercises/conversions/using_as.rs | 4 +--- 5 files changed, 66 insertions(+), 15 deletions(-) diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index c9eed7d015..68084c5379 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -3,24 +3,22 @@ // 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 // Add the AsRef trait appropriately as a trait bound -fn byte_counter(arg: T) -> usize { +fn byte_counter>(arg: T) -> usize { arg.as_ref().as_bytes().len() } // Obtain the number of characters (not bytes) in the given argument // Add the AsRef trait appropriately as a trait bound -fn char_counter(arg: T) -> usize { +fn char_counter>(arg: T) -> usize { arg.as_ref().chars().count() } // Squares a number using as_mut(). Add the trait bound as is appropriate and // implement the function body. -fn num_sq(arg: &mut T) { - ??? +fn num_sq>(arg: &mut T) { + *arg.as_mut() *= *arg.as_mut() } #[cfg(test)] diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs index 6c272c3bcd..8e54aefb0f 100644 --- a/exercises/conversions/from_into.rs +++ b/exercises/conversions/from_into.rs @@ -35,10 +35,35 @@ 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 == "" { + Person::default() + } else { + s.split(",") + .map(|x| x.into()) + .collect::>() + .into() + } + } +} + +impl From> for Person { + fn from(s: Vec) -> Self { + if s.len() != 2 { + return Person::default(); + } + let number = s[1].parse(); + let age; + if number.is_err() || s[0] == "" { + Person::default() + } else { + age = number.unwrap(); + Person { + name: s[0].clone(), + age: age, + } + } } } diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs index fe168159b4..a94829c144 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,24 @@ enum ParsePersonError { impl FromStr for Person { type Err = ParsePersonError; fn from_str(s: &str) -> Result { + if s == "" { + Err(ParsePersonError::Empty) + } else { + let s = s.split(",").map(|x| x.into()).collect::>(); + if s.len() != 2 { + return Err(ParsePersonError::BadLen); + } else if s[0] == "" { + return Err(ParsePersonError::NoName); + } + let number = s[1].parse(); + if let Err(x) = number { + return Err(ParsePersonError::ParseInt(x)); + } + Ok(Person { + name: s[0].clone(), + age: number.unwrap(), + }) + } } } diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index fa98bc90da..b339020ae8 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -23,8 +23,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 +36,16 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + for i in [tuple.0, tuple.1, tuple.2] { + if i < 0 || i > 255 { + return Err(IntoColorError::IntConversion); + } + } + Ok(Color { + red: tuple.0 as u8, + green: tuple.1 as u8, + blue: tuple.2 as u8, + }) } } @@ -45,6 +53,7 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + Color::try_from((arr[0], arr[1], arr[2])) } } @@ -52,6 +61,11 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { + if slice.len() != 3 { + Err(IntoColorError::BadLen) + } else { + Color::try_from((slice[0], slice[1], slice[2])) + } } } diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs index 8c9b7113d8..0d961ca058 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() { From 312f10f1268ed186a547fd78458679a29c19c5b9 Mon Sep 17 00:00:00 2001 From: enforcer007 Date: Sun, 13 Nov 2022 17:20:22 +0530 Subject: [PATCH 31/31] update readme --- README.md | 244 +++++++++++++++++++++++++++--------------------------- 1 file changed, 121 insertions(+), 123 deletions(-) diff --git a/README.md b/README.md index 38972a4bcf..4961e1d0fa 100644 --- a/README.md +++ b/README.md @@ -1,176 +1,174 @@ -# rustlings 🦀❤️ +# Solutions to rustlings 🦀❤️ -Greetings and welcome to `rustlings`. This project contains small exercises to get you used to reading and writing Rust code. This includes reading and responding to compiler messages! +## Solutions to [Rustlings exercises](https://github.com/rust-lang/rustlings) for latest release v5.2.1 -_...looking for the old, web-based version of Rustlings? Try [here](https://github.com/rust-lang/rustlings/tree/rustlings-1)_ +### Topic wise solutions: -Alternatively, for a first-time Rust learner, there are several other resources: +### **intro** +- [intro1](exercises/intro/intro1.rs) +- [intro2](exercises/intro/intro2.rs) -- [The Book](https://doc.rust-lang.org/book/index.html) - The most comprehensive resource for learning Rust, but a bit theoretical sometimes. You will be using this along with Rustlings! -- [Rust By Example](https://doc.rust-lang.org/rust-by-example/index.html) - Learn Rust by solving little exercises! It's almost like `rustlings`, but online -## Getting Started +### **variables** +- [variables1](exercises/variables/variables1.rs) +- [variables2](exercises/variables/variables2.rs) +- [variables3](exercises/variables/variables3.rs) +- [variables4](exercises/variables/variables4.rs) +- [variables5](exercises/variables/variables5.rs) +- [variables6](exercises/variables/variables6.rs) -_Note: If you're on MacOS, make sure you've installed Xcode and its developer tools by typing `xcode-select --install`._ -_Note: If you're on Linux, make sure you've installed gcc. Deb: `sudo apt install gcc`. Yum: `sudo yum -y install gcc`._ -You will need to have Rust installed. You can get it by visiting https://rustup.rs. This'll also install Cargo, Rust's package/project manager. +### **functions** +- [functions1](exercises/functions/functions1.rs) +- [functions2](exercises/functions/functions2.rs) +- [functions3](exercises/functions/functions3.rs) +- [functions4](exercises/functions/functions4.rs) +- [functions5](exercises/functions/functions5.rs) -## MacOS/Linux -Just run: +### **if** +- [if1](exercises/if/if1.rs) +- [if2](exercises/if/if2.rs) -```bash -curl -L https://raw.githubusercontent.com/rust-lang/rustlings/main/install.sh | bash -# Or if you want it to be installed to a different path: -curl -L https://raw.githubusercontent.com/rust-lang/rustlings/main/install.sh | bash -s mypath/ -``` -This will install Rustlings and give you access to the `rustlings` command. Run it to get started! +### **quiz1** +- [quiz1](exercises/quiz1.rs) -### Nix -Basically: Clone the repository at the latest tag, finally run `nix develop` or `nix-shell`. -```bash -# find out the latest version at https://github.com/rust-lang/rustlings/releases/latest (on edit 5.2.1) -git clone -b 5.2.1 --depth 1 https://github.com/rust-lang/rustlings -cd rustlings -# if nix version > 2.3 -nix develop -# if nix version <= 2.3 -nix-shell -``` +### **primitive_types** +- [primitive_types1](exercises/primitive_types/primitive_types1.rs) +- [primitive_types2](exercises/primitive_types/primitive_types2.rs) +- [primitive_types3](exercises/primitive_types/primitive_types3.rs) +- [primitive_types4](exercises/primitive_types/primitive_types4.rs) +- [primitive_types5](exercises/primitive_types/primitive_types5.rs) +- [primitive_types6](exercises/primitive_types/primitive_types6.rs) -## Windows -In PowerShell (Run as Administrator), set `ExecutionPolicy` to `RemoteSigned`: +### **vecs** +- [vecs1](exercises/vecs/vecs1.rs) +- [vecs2](exercises/vecs/vecs2.rs) -```ps1 -Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -``` -Then, you can run: +### **move_semantics** +- [move_semantics1](exercises/move_semantics/move_semantics1.rs) +- [move_semantics2](exercises/move_semantics/move_semantics2.rs) +- [move_semantics3](exercises/move_semantics/move_semantics3.rs) +- [move_semantics4](exercises/move_semantics/move_semantics4.rs) +- [move_semantics5](exercises/move_semantics/move_semantics5.rs) +- [move_semantics6](exercises/move_semantics/move_semantics6.rs) -```ps1 -Start-BitsTransfer -Source https://raw.githubusercontent.com/rust-lang/rustlings/main/install.ps1 -Destination $env:TMP/install_rustlings.ps1; Unblock-File $env:TMP/install_rustlings.ps1; Invoke-Expression $env:TMP/install_rustlings.ps1 -``` -To install Rustlings. Same as on MacOS/Linux, you will have access to the `rustlings` command after it. +### **structs** +- [structs1](exercises/structs/structs1.rs) +- [structs2](exercises/structs/structs2.rs) +- [structs3](exercises/structs/structs3.rs) -If you get a permission denied message, you might have to exclude the directory where you cloned Rustlings in your antivirus. -## Browser +### **enums** +- [enums1](exercises/enums/enums1.rs) +- [enums2](exercises/enums/enums2.rs) +- [enums3](exercises/enums/enums3.rs) -[Run on Repl.it](https://repl.it/github/rust-lang/rustlings) -[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/rust-lang/rustlings) +### **strings** +- [strings1](exercises/strings/strings1.rs) +- [strings2](exercises/strings/strings2.rs) +- [strings3](exercises/strings/strings3.rs) +- [strings4](exercises/strings/strings4.rs) -## Manually -Basically: Clone the repository at the latest tag, run `cargo install --path .`. +### **modules** +- [modules1](exercises/modules/modules1.rs) +- [modules2](exercises/modules/modules2.rs) +- [modules3](exercises/modules/modules3.rs) -```bash -# find out the latest version at https://github.com/rust-lang/rustlings/releases/latest (on edit 5.2.1) -git clone -b 5.2.1 --depth 1 https://github.com/rust-lang/rustlings -cd rustlings -cargo install --force --path . -``` -If there are installation errors, ensure that your toolchain is up to date. For the latest, run: +### **hashmaps** +- [hashmaps1](exercises/hashmaps/hashmaps1.rs) +- [hashmaps2](exercises/hashmaps/hashmaps2.rs) +- [hashmaps3](exercises/hashmaps/hashmaps3.rs) -```bash -rustup update -``` -Then, same as above, run `rustlings` to get started. +### **quiz2** +- [quiz2](exercises/quiz2.rs) -## Doing exercises -The exercises are sorted by topic and can be found in the subdirectory `rustlings/exercises/`. For every topic there is an additional README file with some resources to get you started on the topic. We really recommend that you have a look at them before you start. +### **options** +- [options1](exercises/options/options1.rs) +- [options2](exercises/options/options2.rs) +- [options3](exercises/options/options3.rs) -The task is simple. Most exercises contain an error that keeps them from compiling, and it's up to you to fix it! Some exercises are also run as tests, but rustlings handles them all the same. To run the exercises in the recommended order, execute: -```bash -rustlings watch -``` +### **error_handling** +- [errors1](exercises/error_handling/errors1.rs) +- [errors2](exercises/error_handling/errors2.rs) +- [errors3](exercises/error_handling/errors3.rs) +- [errors4](exercises/error_handling/errors4.rs) +- [errors5](exercises/error_handling/errors5.rs) +- [errors6](exercises/error_handling/errors6.rs) -This will try to verify the completion of every exercise in a predetermined order (what we think is best for newcomers). It will also rerun automatically every time you change a file in the `exercises/` directory. If you want to only run it once, you can use: -```bash -rustlings verify -``` +### **generics** +- [generics1](exercises/generics/generics1.rs) +- [generics2](exercises/generics/generics2.rs) -This will do the same as watch, but it'll quit after running. -In case you want to go by your own order, or want to only verify a single exercise, you can run: +### **traits** +- [traits1](exercises/traits/traits1.rs) +- [traits2](exercises/traits/traits2.rs) +- [traits3](exercises/traits/traits3.rs) +- [traits4](exercises/traits/traits4.rs) +- [traits5](exercises/traits/traits5.rs) -```bash -rustlings run myExercise1 -``` -Or simply use the following command to run the next unsolved exercise in the course: +### **quiz3** +- [quiz3](exercises/quiz3.rs) -```bash -rustlings run next -``` -In case you get stuck, you can run the following command to get a hint for your -exercise: +### **tests** +- [tests1](exercises/tests/tests1.rs) +- [tests2](exercises/tests/tests2.rs) +- [tests3](exercises/tests/tests3.rs) -```bash -rustlings hint myExercise1 -``` -You can also get the hint for the next unsolved exercise with the following command: +### **lifetimes** +- [lifetimes1](exercises/lifetimes/lifetimes1.rs) +- [lifetimes2](exercises/lifetimes/lifetimes2.rs) +- [lifetimes3](exercises/lifetimes/lifetimes3.rs) -```bash -rustlings hint next -``` -To check your progress, you can run the following command: +### **standard_library_types** +- [iterators1](exercises/standard_library_types/iterators1.rs) +- [iterators2](exercises/standard_library_types/iterators2.rs) +- [iterators3](exercises/standard_library_types/iterators3.rs) +- [iterators4](exercises/standard_library_types/iterators4.rs) +- [iterators5](exercises/standard_library_types/iterators5.rs) +- [box1](exercises/standard_library_types/box1.rs) +- [arc1](exercises/standard_library_types/arc1.rs) -```bash -rustlings list -``` -## Testing yourself +### **threads** +- [threads1](exercises/threads/threads1.rs) +- [threads2](exercises/threads/threads2.rs) +- [threads3](exercises/threads/threads3.rs) -After every couple of sections, there will be a quiz that'll test your knowledge on a bunch of sections at once. These quizzes are found in `exercises/quizN.rs`. -## Enabling `rust-analyzer` +### **macros** +- [macros1](exercises/macros/macros1.rs) +- [macros2](exercises/macros/macros2.rs) +- [macros3](exercises/macros/macros3.rs) +- [macros4](exercises/macros/macros4.rs) -Run the command `rustlings lsp` which will generate a `rust-project.json` at the root of the project, this allows [rust-analyzer](https://rust-analyzer.github.io/) to parse each exercise. -## Continuing On +### **clippy** +- [clippy1](exercises/clippy/clippy1.rs) +- [clippy2](exercises/clippy/clippy2.rs) +- [clippy3](exercises/clippy/clippy3.rs) -Once you've completed Rustlings, put your new knowledge to good use! Continue practicing your Rust skills by building your own projects, contributing to Rustlings, or finding other open-source projects to contribute to. -## Uninstalling Rustlings - -If you want to remove Rustlings from your system, there are two steps. First, you'll need to remove the exercises folder that the install script created -for you: - -```bash -rm -rf rustlings # or your custom folder name, if you chose and or renamed it -``` - -Second, since Rustlings got installed via `cargo install`, it's only reasonable to assume that you can also remove it using Cargo, and -exactly that is the case. Run `cargo uninstall` to remove the `rustlings` binary: - -```bash -cargo uninstall rustlings -``` - -Now you should be done! - -## Contributing - -See [CONTRIBUTING.md](./CONTRIBUTING.md). - -Development-focused discussion about Rustlings happens in the [**rustlings** stream](https://rust-lang.zulipchat.com/#narrow/stream/334454-rustlings) -on the [Rust Project Zulip](https://rust-lang.zulipchat.com). Feel free to start a new thread there -if you have ideas or suggestions! - -## Contributors ✨ - -Thanks goes to the wonderful people listed in [AUTHORS.md](./AUTHORS.md) 🎉 +### **conversions** +- [using_as](exercises/conversions/using_as.rs) +- [from_into](exercises/conversions/from_into.rs) +- [from_str](exercises/conversions/from_str.rs) +- [try_from_into](exercises/conversions/try_from_into.rs) +- [as_ref_mut](exercises/conversions/as_ref_mut.rs) \ No newline at end of file