From 64d95837e9813541cf5b357de13865ce687ae98d Mon Sep 17 00:00:00 2001 From: Adam Brewer Date: Mon, 16 Oct 2023 07:37:12 -0400 Subject: Update Exercises Directory Names to Reflect Order --- exercises/00_intro/README.md | 8 + exercises/00_intro/intro1.rs | 41 +++++ exercises/00_intro/intro2.rs | 12 ++ exercises/01_variables/README.md | 9 ++ exercises/01_variables/variables1.rs | 13 ++ exercises/01_variables/variables2.rs | 15 ++ exercises/01_variables/variables3.rs | 11 ++ exercises/01_variables/variables4.rs | 13 ++ exercises/01_variables/variables5.rs | 13 ++ exercises/01_variables/variables6.rs | 11 ++ exercises/02_functions/README.md | 8 + exercises/02_functions/functions1.rs | 10 ++ exercises/02_functions/functions2.rs | 16 ++ exercises/02_functions/functions3.rs | 16 ++ exercises/02_functions/functions4.rs | 28 ++++ exercises/02_functions/functions5.rs | 15 ++ exercises/03_if/README.md | 7 + exercises/03_if/if1.rs | 33 ++++ exercises/03_if/if2.rs | 37 +++++ exercises/03_if/if3.rs | 56 +++++++ exercises/04_primitive_types/README.md | 9 ++ exercises/04_primitive_types/primitive_types1.rs | 20 +++ exercises/04_primitive_types/primitive_types2.rs | 32 ++++ exercises/04_primitive_types/primitive_types3.rs | 19 +++ exercises/04_primitive_types/primitive_types4.rs | 17 ++ exercises/04_primitive_types/primitive_types5.rs | 15 ++ exercises/04_primitive_types/primitive_types6.rs | 19 +++ exercises/05_vecs/README.md | 17 ++ exercises/05_vecs/vecs1.rs | 28 ++++ exercises/05_vecs/vecs2.rs | 50 ++++++ exercises/06_move_semantics/README.md | 10 ++ exercises/06_move_semantics/move_semantics1.rs | 23 +++ exercises/06_move_semantics/move_semantics2.rs | 26 +++ exercises/06_move_semantics/move_semantics3.rs | 24 +++ exercises/06_move_semantics/move_semantics4.rs | 29 ++++ exercises/06_move_semantics/move_semantics5.rs | 19 +++ exercises/06_move_semantics/move_semantics6.rs | 28 ++++ exercises/07_structs/README.md | 8 + exercises/07_structs/structs1.rs | 51 ++++++ exercises/07_structs/structs2.rs | 50 ++++++ exercises/07_structs/structs3.rs | 88 +++++++++++ exercises/08_enums/README.md | 10 ++ exercises/08_enums/enums1.rs | 17 ++ exercises/08_enums/enums2.rs | 30 ++++ exercises/08_enums/enums3.rs | 73 +++++++++ exercises/09_strings/README.md | 9 ++ exercises/09_strings/strings1.rs | 17 ++ exercises/09_strings/strings2.rs | 21 +++ exercises/09_strings/strings3.rs | 45 ++++++ exercises/09_strings/strings4.rs | 30 ++++ exercises/10_modules/README.md | 7 + exercises/10_modules/modules1.rs | 22 +++ exercises/10_modules/modules2.rs | 34 ++++ exercises/10_modules/modules3.rs | 21 +++ exercises/11_hashmaps/README.md | 12 ++ exercises/11_hashmaps/hashmaps1.rs | 44 ++++++ exercises/11_hashmaps/hashmaps2.rs | 93 +++++++++++ exercises/11_hashmaps/hashmaps3.rs | 86 ++++++++++ exercises/12_options/README.md | 21 +++ exercises/12_options/options1.rs | 39 +++++ exercises/12_options/options2.rs | 42 +++++ exercises/12_options/options3.rs | 21 +++ exercises/13_error_handling/README.md | 12 ++ exercises/13_error_handling/errors1.rs | 43 +++++ exercises/13_error_handling/errors2.rs | 50 ++++++ exercises/13_error_handling/errors3.rs | 34 ++++ exercises/13_error_handling/errors4.rs | 32 ++++ exercises/13_error_handling/errors5.rs | 71 +++++++++ exercises/13_error_handling/errors6.rs | 94 +++++++++++ exercises/14_generics/README.md | 11 ++ exercises/14_generics/generics1.rs | 14 ++ exercises/14_generics/generics2.rs | 34 ++++ exercises/15_traits/README.md | 19 +++ exercises/15_traits/traits1.rs | 42 +++++ exercises/15_traits/traits2.rs | 29 ++++ exercises/15_traits/traits3.rs | 42 +++++ exercises/15_traits/traits4.rs | 49 ++++++ exercises/15_traits/traits5.rs | 40 +++++ exercises/16_lifetimes/README.md | 22 +++ exercises/16_lifetimes/lifetimes1.rs | 27 ++++ exercises/16_lifetimes/lifetimes2.rs | 27 ++++ exercises/16_lifetimes/lifetimes3.rs | 21 +++ exercises/17_tests/README.md | 7 + exercises/17_tests/tests1.rs | 21 +++ exercises/17_tests/tests2.rs | 17 ++ exercises/17_tests/tests3.rs | 29 ++++ exercises/17_tests/tests4.rs | 48 ++++++ exercises/18_iterators/README.md | 8 + exercises/18_iterators/iterators1.rs | 26 +++ exercises/18_iterators/iterators2.rs | 63 ++++++++ exercises/18_iterators/iterators3.rs | 90 +++++++++++ exercises/18_iterators/iterators4.rs | 42 +++++ exercises/18_iterators/iterators5.rs | 156 ++++++++++++++++++ exercises/19_smart_pointers/README.md | 12 ++ exercises/19_smart_pointers/arc1.rs | 45 ++++++ exercises/19_smart_pointers/box1.rs | 58 +++++++ exercises/19_smart_pointers/cow1.rs | 78 +++++++++ exercises/19_smart_pointers/rc1.rs | 105 ++++++++++++ exercises/20_threads/README.md | 9 ++ exercises/20_threads/threads1.rs | 40 +++++ exercises/20_threads/threads2.rs | 39 +++++ exercises/20_threads/threads3.rs | 67 ++++++++ exercises/21_macros/README.md | 14 ++ exercises/21_macros/macros1.rs | 16 ++ exercises/21_macros/macros2.rs | 16 ++ exercises/21_macros/macros3.rs | 20 +++ exercises/21_macros/macros4.rs | 21 +++ exercises/22_clippy/README.md | 10 ++ exercises/22_clippy/clippy1.rs | 26 +++ exercises/22_clippy/clippy2.rs | 15 ++ exercises/22_clippy/clippy3.rs | 30 ++++ exercises/23_conversions/README.md | 23 +++ exercises/23_conversions/as_ref_mut.rs | 65 ++++++++ exercises/23_conversions/from_into.rs | 140 ++++++++++++++++ exercises/23_conversions/from_str.rs | 133 ++++++++++++++++ exercises/23_conversions/try_from_into.rs | 193 +++++++++++++++++++++++ exercises/23_conversions/using_as.rs | 33 ++++ exercises/clippy/README.md | 10 -- exercises/clippy/clippy1.rs | 26 --- exercises/clippy/clippy2.rs | 15 -- exercises/clippy/clippy3.rs | 30 ---- exercises/conversions/README.md | 23 --- exercises/conversions/as_ref_mut.rs | 65 -------- exercises/conversions/from_into.rs | 140 ---------------- exercises/conversions/from_str.rs | 133 ---------------- exercises/conversions/try_from_into.rs | 193 ----------------------- exercises/conversions/using_as.rs | 33 ---- exercises/enums/README.md | 10 -- exercises/enums/enums1.rs | 17 -- exercises/enums/enums2.rs | 30 ---- exercises/enums/enums3.rs | 73 --------- exercises/error_handling/README.md | 12 -- exercises/error_handling/errors1.rs | 43 ----- exercises/error_handling/errors2.rs | 50 ------ exercises/error_handling/errors3.rs | 34 ---- exercises/error_handling/errors4.rs | 32 ---- exercises/error_handling/errors5.rs | 71 --------- exercises/error_handling/errors6.rs | 94 ----------- exercises/functions/README.md | 8 - exercises/functions/functions1.rs | 10 -- exercises/functions/functions2.rs | 16 -- exercises/functions/functions3.rs | 16 -- exercises/functions/functions4.rs | 28 ---- exercises/functions/functions5.rs | 15 -- exercises/generics/README.md | 11 -- exercises/generics/generics1.rs | 14 -- exercises/generics/generics2.rs | 34 ---- exercises/hashmaps/README.md | 12 -- exercises/hashmaps/hashmaps1.rs | 44 ------ exercises/hashmaps/hashmaps2.rs | 93 ----------- exercises/hashmaps/hashmaps3.rs | 86 ---------- exercises/if/README.md | 7 - exercises/if/if1.rs | 33 ---- exercises/if/if2.rs | 37 ----- exercises/if/if3.rs | 56 ------- exercises/intro/README.md | 8 - exercises/intro/intro1.rs | 41 ----- exercises/intro/intro2.rs | 12 -- exercises/iterators/README.md | 8 - exercises/iterators/iterators1.rs | 26 --- exercises/iterators/iterators2.rs | 63 -------- exercises/iterators/iterators3.rs | 90 ----------- exercises/iterators/iterators4.rs | 42 ----- exercises/iterators/iterators5.rs | 156 ------------------ exercises/lifetimes/README.md | 22 --- exercises/lifetimes/lifetimes1.rs | 27 ---- exercises/lifetimes/lifetimes2.rs | 27 ---- exercises/lifetimes/lifetimes3.rs | 21 --- exercises/macros/README.md | 14 -- exercises/macros/macros1.rs | 16 -- exercises/macros/macros2.rs | 16 -- exercises/macros/macros3.rs | 20 --- exercises/macros/macros4.rs | 21 --- exercises/modules/README.md | 7 - exercises/modules/modules1.rs | 22 --- exercises/modules/modules2.rs | 34 ---- exercises/modules/modules3.rs | 21 --- exercises/move_semantics/README.md | 10 -- exercises/move_semantics/move_semantics1.rs | 23 --- exercises/move_semantics/move_semantics2.rs | 26 --- exercises/move_semantics/move_semantics3.rs | 24 --- exercises/move_semantics/move_semantics4.rs | 29 ---- exercises/move_semantics/move_semantics5.rs | 19 --- exercises/move_semantics/move_semantics6.rs | 28 ---- exercises/options/README.md | 21 --- exercises/options/options1.rs | 39 ----- exercises/options/options2.rs | 42 ----- exercises/options/options3.rs | 21 --- exercises/primitive_types/README.md | 9 -- exercises/primitive_types/primitive_types1.rs | 20 --- exercises/primitive_types/primitive_types2.rs | 32 ---- exercises/primitive_types/primitive_types3.rs | 19 --- exercises/primitive_types/primitive_types4.rs | 17 -- exercises/primitive_types/primitive_types5.rs | 15 -- exercises/primitive_types/primitive_types6.rs | 19 --- exercises/smart_pointers/README.md | 12 -- exercises/smart_pointers/arc1.rs | 45 ------ exercises/smart_pointers/box1.rs | 58 ------- exercises/smart_pointers/cow1.rs | 78 --------- exercises/smart_pointers/rc1.rs | 105 ------------ exercises/strings/README.md | 9 -- exercises/strings/strings1.rs | 17 -- exercises/strings/strings2.rs | 21 --- exercises/strings/strings3.rs | 45 ------ exercises/strings/strings4.rs | 30 ---- exercises/structs/README.md | 8 - exercises/structs/structs1.rs | 51 ------ exercises/structs/structs2.rs | 50 ------ exercises/structs/structs3.rs | 88 ----------- exercises/tests/README.md | 7 - exercises/tests/tests1.rs | 21 --- exercises/tests/tests2.rs | 17 -- exercises/tests/tests3.rs | 29 ---- exercises/tests/tests4.rs | 48 ------ exercises/threads/README.md | 9 -- exercises/threads/threads1.rs | 40 ----- exercises/threads/threads2.rs | 39 ----- exercises/threads/threads3.rs | 67 -------- exercises/traits/README.md | 19 --- exercises/traits/traits1.rs | 42 ----- exercises/traits/traits2.rs | 29 ---- exercises/traits/traits3.rs | 42 ----- exercises/traits/traits4.rs | 49 ------ exercises/traits/traits5.rs | 40 ----- exercises/variables/README.md | 9 -- exercises/variables/variables1.rs | 13 -- exercises/variables/variables2.rs | 15 -- exercises/variables/variables3.rs | 11 -- exercises/variables/variables4.rs | 13 -- exercises/variables/variables5.rs | 13 -- exercises/variables/variables6.rs | 11 -- exercises/vecs/README.md | 17 -- exercises/vecs/vecs1.rs | 28 ---- exercises/vecs/vecs2.rs | 50 ------ info.toml | 188 +++++++++++----------- 235 files changed, 4170 insertions(+), 4170 deletions(-) create mode 100644 exercises/00_intro/README.md create mode 100644 exercises/00_intro/intro1.rs create mode 100644 exercises/00_intro/intro2.rs create mode 100644 exercises/01_variables/README.md create mode 100644 exercises/01_variables/variables1.rs create mode 100644 exercises/01_variables/variables2.rs create mode 100644 exercises/01_variables/variables3.rs create mode 100644 exercises/01_variables/variables4.rs create mode 100644 exercises/01_variables/variables5.rs create mode 100644 exercises/01_variables/variables6.rs create mode 100644 exercises/02_functions/README.md create mode 100644 exercises/02_functions/functions1.rs create mode 100644 exercises/02_functions/functions2.rs create mode 100644 exercises/02_functions/functions3.rs create mode 100644 exercises/02_functions/functions4.rs create mode 100644 exercises/02_functions/functions5.rs create mode 100644 exercises/03_if/README.md create mode 100644 exercises/03_if/if1.rs create mode 100644 exercises/03_if/if2.rs create mode 100644 exercises/03_if/if3.rs create mode 100644 exercises/04_primitive_types/README.md create mode 100644 exercises/04_primitive_types/primitive_types1.rs create mode 100644 exercises/04_primitive_types/primitive_types2.rs create mode 100644 exercises/04_primitive_types/primitive_types3.rs create mode 100644 exercises/04_primitive_types/primitive_types4.rs create mode 100644 exercises/04_primitive_types/primitive_types5.rs create mode 100644 exercises/04_primitive_types/primitive_types6.rs create mode 100644 exercises/05_vecs/README.md create mode 100644 exercises/05_vecs/vecs1.rs create mode 100644 exercises/05_vecs/vecs2.rs create mode 100644 exercises/06_move_semantics/README.md create mode 100644 exercises/06_move_semantics/move_semantics1.rs create mode 100644 exercises/06_move_semantics/move_semantics2.rs create mode 100644 exercises/06_move_semantics/move_semantics3.rs create mode 100644 exercises/06_move_semantics/move_semantics4.rs create mode 100644 exercises/06_move_semantics/move_semantics5.rs create mode 100644 exercises/06_move_semantics/move_semantics6.rs create mode 100644 exercises/07_structs/README.md create mode 100644 exercises/07_structs/structs1.rs create mode 100644 exercises/07_structs/structs2.rs create mode 100644 exercises/07_structs/structs3.rs create mode 100644 exercises/08_enums/README.md create mode 100644 exercises/08_enums/enums1.rs create mode 100644 exercises/08_enums/enums2.rs create mode 100644 exercises/08_enums/enums3.rs create mode 100644 exercises/09_strings/README.md create mode 100644 exercises/09_strings/strings1.rs create mode 100644 exercises/09_strings/strings2.rs create mode 100644 exercises/09_strings/strings3.rs create mode 100644 exercises/09_strings/strings4.rs create mode 100644 exercises/10_modules/README.md create mode 100644 exercises/10_modules/modules1.rs create mode 100644 exercises/10_modules/modules2.rs create mode 100644 exercises/10_modules/modules3.rs create mode 100644 exercises/11_hashmaps/README.md create mode 100644 exercises/11_hashmaps/hashmaps1.rs create mode 100644 exercises/11_hashmaps/hashmaps2.rs create mode 100644 exercises/11_hashmaps/hashmaps3.rs create mode 100644 exercises/12_options/README.md create mode 100644 exercises/12_options/options1.rs create mode 100644 exercises/12_options/options2.rs create mode 100644 exercises/12_options/options3.rs create mode 100644 exercises/13_error_handling/README.md create mode 100644 exercises/13_error_handling/errors1.rs create mode 100644 exercises/13_error_handling/errors2.rs create mode 100644 exercises/13_error_handling/errors3.rs create mode 100644 exercises/13_error_handling/errors4.rs create mode 100644 exercises/13_error_handling/errors5.rs create mode 100644 exercises/13_error_handling/errors6.rs create mode 100644 exercises/14_generics/README.md create mode 100644 exercises/14_generics/generics1.rs create mode 100644 exercises/14_generics/generics2.rs create mode 100644 exercises/15_traits/README.md create mode 100644 exercises/15_traits/traits1.rs create mode 100644 exercises/15_traits/traits2.rs create mode 100644 exercises/15_traits/traits3.rs create mode 100644 exercises/15_traits/traits4.rs create mode 100644 exercises/15_traits/traits5.rs create mode 100644 exercises/16_lifetimes/README.md create mode 100644 exercises/16_lifetimes/lifetimes1.rs create mode 100644 exercises/16_lifetimes/lifetimes2.rs create mode 100644 exercises/16_lifetimes/lifetimes3.rs create mode 100644 exercises/17_tests/README.md create mode 100644 exercises/17_tests/tests1.rs create mode 100644 exercises/17_tests/tests2.rs create mode 100644 exercises/17_tests/tests3.rs create mode 100644 exercises/17_tests/tests4.rs create mode 100644 exercises/18_iterators/README.md create mode 100644 exercises/18_iterators/iterators1.rs create mode 100644 exercises/18_iterators/iterators2.rs create mode 100644 exercises/18_iterators/iterators3.rs create mode 100644 exercises/18_iterators/iterators4.rs create mode 100644 exercises/18_iterators/iterators5.rs create mode 100644 exercises/19_smart_pointers/README.md create mode 100644 exercises/19_smart_pointers/arc1.rs create mode 100644 exercises/19_smart_pointers/box1.rs create mode 100644 exercises/19_smart_pointers/cow1.rs create mode 100644 exercises/19_smart_pointers/rc1.rs create mode 100644 exercises/20_threads/README.md create mode 100644 exercises/20_threads/threads1.rs create mode 100644 exercises/20_threads/threads2.rs create mode 100644 exercises/20_threads/threads3.rs create mode 100644 exercises/21_macros/README.md create mode 100644 exercises/21_macros/macros1.rs create mode 100644 exercises/21_macros/macros2.rs create mode 100644 exercises/21_macros/macros3.rs create mode 100644 exercises/21_macros/macros4.rs create mode 100644 exercises/22_clippy/README.md create mode 100644 exercises/22_clippy/clippy1.rs create mode 100644 exercises/22_clippy/clippy2.rs create mode 100644 exercises/22_clippy/clippy3.rs create mode 100644 exercises/23_conversions/README.md create mode 100644 exercises/23_conversions/as_ref_mut.rs create mode 100644 exercises/23_conversions/from_into.rs create mode 100644 exercises/23_conversions/from_str.rs create mode 100644 exercises/23_conversions/try_from_into.rs create mode 100644 exercises/23_conversions/using_as.rs delete mode 100644 exercises/clippy/README.md delete mode 100644 exercises/clippy/clippy1.rs delete mode 100644 exercises/clippy/clippy2.rs delete mode 100644 exercises/clippy/clippy3.rs delete mode 100644 exercises/conversions/README.md delete mode 100644 exercises/conversions/as_ref_mut.rs delete mode 100644 exercises/conversions/from_into.rs delete mode 100644 exercises/conversions/from_str.rs delete mode 100644 exercises/conversions/try_from_into.rs delete mode 100644 exercises/conversions/using_as.rs delete mode 100644 exercises/enums/README.md delete mode 100644 exercises/enums/enums1.rs delete mode 100644 exercises/enums/enums2.rs delete mode 100644 exercises/enums/enums3.rs delete mode 100644 exercises/error_handling/README.md delete mode 100644 exercises/error_handling/errors1.rs delete mode 100644 exercises/error_handling/errors2.rs delete mode 100644 exercises/error_handling/errors3.rs delete mode 100644 exercises/error_handling/errors4.rs delete mode 100644 exercises/error_handling/errors5.rs delete mode 100644 exercises/error_handling/errors6.rs delete mode 100644 exercises/functions/README.md delete mode 100644 exercises/functions/functions1.rs delete mode 100644 exercises/functions/functions2.rs delete mode 100644 exercises/functions/functions3.rs delete mode 100644 exercises/functions/functions4.rs delete mode 100644 exercises/functions/functions5.rs delete mode 100644 exercises/generics/README.md delete mode 100644 exercises/generics/generics1.rs delete mode 100644 exercises/generics/generics2.rs delete mode 100644 exercises/hashmaps/README.md delete mode 100644 exercises/hashmaps/hashmaps1.rs delete mode 100644 exercises/hashmaps/hashmaps2.rs delete mode 100644 exercises/hashmaps/hashmaps3.rs delete mode 100644 exercises/if/README.md delete mode 100644 exercises/if/if1.rs delete mode 100644 exercises/if/if2.rs delete mode 100644 exercises/if/if3.rs delete mode 100644 exercises/intro/README.md delete mode 100644 exercises/intro/intro1.rs delete mode 100644 exercises/intro/intro2.rs delete mode 100644 exercises/iterators/README.md delete mode 100644 exercises/iterators/iterators1.rs delete mode 100644 exercises/iterators/iterators2.rs delete mode 100644 exercises/iterators/iterators3.rs delete mode 100644 exercises/iterators/iterators4.rs delete mode 100644 exercises/iterators/iterators5.rs delete mode 100644 exercises/lifetimes/README.md delete mode 100644 exercises/lifetimes/lifetimes1.rs delete mode 100644 exercises/lifetimes/lifetimes2.rs delete mode 100644 exercises/lifetimes/lifetimes3.rs delete mode 100644 exercises/macros/README.md delete mode 100644 exercises/macros/macros1.rs delete mode 100644 exercises/macros/macros2.rs delete mode 100644 exercises/macros/macros3.rs delete mode 100644 exercises/macros/macros4.rs delete mode 100644 exercises/modules/README.md delete mode 100644 exercises/modules/modules1.rs delete mode 100644 exercises/modules/modules2.rs delete mode 100644 exercises/modules/modules3.rs delete mode 100644 exercises/move_semantics/README.md delete mode 100644 exercises/move_semantics/move_semantics1.rs delete mode 100644 exercises/move_semantics/move_semantics2.rs delete mode 100644 exercises/move_semantics/move_semantics3.rs delete mode 100644 exercises/move_semantics/move_semantics4.rs delete mode 100644 exercises/move_semantics/move_semantics5.rs delete mode 100644 exercises/move_semantics/move_semantics6.rs delete mode 100644 exercises/options/README.md delete mode 100644 exercises/options/options1.rs delete mode 100644 exercises/options/options2.rs delete mode 100644 exercises/options/options3.rs delete mode 100644 exercises/primitive_types/README.md delete mode 100644 exercises/primitive_types/primitive_types1.rs delete mode 100644 exercises/primitive_types/primitive_types2.rs delete mode 100644 exercises/primitive_types/primitive_types3.rs delete mode 100644 exercises/primitive_types/primitive_types4.rs delete mode 100644 exercises/primitive_types/primitive_types5.rs delete mode 100644 exercises/primitive_types/primitive_types6.rs delete mode 100644 exercises/smart_pointers/README.md delete mode 100644 exercises/smart_pointers/arc1.rs delete mode 100644 exercises/smart_pointers/box1.rs delete mode 100644 exercises/smart_pointers/cow1.rs delete mode 100644 exercises/smart_pointers/rc1.rs delete mode 100644 exercises/strings/README.md delete mode 100644 exercises/strings/strings1.rs delete mode 100644 exercises/strings/strings2.rs delete mode 100644 exercises/strings/strings3.rs delete mode 100644 exercises/strings/strings4.rs delete mode 100644 exercises/structs/README.md delete mode 100644 exercises/structs/structs1.rs delete mode 100644 exercises/structs/structs2.rs delete mode 100644 exercises/structs/structs3.rs delete mode 100644 exercises/tests/README.md delete mode 100644 exercises/tests/tests1.rs delete mode 100644 exercises/tests/tests2.rs delete mode 100644 exercises/tests/tests3.rs delete mode 100644 exercises/tests/tests4.rs delete mode 100644 exercises/threads/README.md delete mode 100644 exercises/threads/threads1.rs delete mode 100644 exercises/threads/threads2.rs delete mode 100644 exercises/threads/threads3.rs delete mode 100644 exercises/traits/README.md delete mode 100644 exercises/traits/traits1.rs delete mode 100644 exercises/traits/traits2.rs delete mode 100644 exercises/traits/traits3.rs delete mode 100644 exercises/traits/traits4.rs delete mode 100644 exercises/traits/traits5.rs delete mode 100644 exercises/variables/README.md delete mode 100644 exercises/variables/variables1.rs delete mode 100644 exercises/variables/variables2.rs delete mode 100644 exercises/variables/variables3.rs delete mode 100644 exercises/variables/variables4.rs delete mode 100644 exercises/variables/variables5.rs delete mode 100644 exercises/variables/variables6.rs delete mode 100644 exercises/vecs/README.md delete mode 100644 exercises/vecs/vecs1.rs delete mode 100644 exercises/vecs/vecs2.rs diff --git a/exercises/00_intro/README.md b/exercises/00_intro/README.md new file mode 100644 index 0000000..d32e4a8 --- /dev/null +++ b/exercises/00_intro/README.md @@ -0,0 +1,8 @@ +# Intro + +Rust uses the `print!` and `println!` macros to print text to the console. + +## Further information + +- [Hello World](https://doc.rust-lang.org/rust-by-example/hello.html) +- [Formatted print](https://doc.rust-lang.org/rust-by-example/hello/print.html) diff --git a/exercises/00_intro/intro1.rs b/exercises/00_intro/intro1.rs new file mode 100644 index 0000000..c5196d6 --- /dev/null +++ b/exercises/00_intro/intro1.rs @@ -0,0 +1,41 @@ +// intro1.rs +// +// About this `I AM NOT DONE` thing: +// We sometimes encourage you to keep trying things on a given exercise, even +// after you already figured it out. If you got everything working and feel +// ready for the next exercise, remove the `I AM NOT DONE` comment below. +// +// If you're running this using `rustlings watch`: The exercise file will be +// reloaded 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! +// +// Execute `rustlings hint intro1` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + println!("Hello and"); + println!(r#" welcome to... "#); + println!(r#" _ _ _ "#); + println!(r#" _ __ _ _ ___| |_| (_)_ __ __ _ ___ "#); + println!(r#" | '__| | | / __| __| | | '_ \ / _` / __| "#); + println!(r#" | | | |_| \__ \ |_| | | | | | (_| \__ \ "#); + println!(r#" |_| \__,_|___/\__|_|_|_| |_|\__, |___/ "#); + println!(r#" |___/ "#); + println!(); + println!("This exercise compiles successfully. The remaining exercises contain a compiler"); + println!("or logic error. The central concept behind Rustlings is to fix these errors and"); + println!("solve the exercises. Good luck!"); + println!(); + println!("The source for this exercise is in `exercises/intro00/intro1.rs`. Have a look!"); + println!( + "Going forward, the source of the exercises will always be in the success/failure output." + ); + println!(); + println!( + "If you want to use rust-analyzer, Rust's LSP implementation, make sure your editor is set" + ); + println!("up, and then run `rustlings lsp` before continuing.") +} diff --git a/exercises/00_intro/intro2.rs b/exercises/00_intro/intro2.rs new file mode 100644 index 0000000..990b20f --- /dev/null +++ b/exercises/00_intro/intro2.rs @@ -0,0 +1,12 @@ +// intro2.rs +// +// 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 {}!"); +} diff --git a/exercises/01_variables/README.md b/exercises/01_variables/README.md new file mode 100644 index 0000000..7964ff2 --- /dev/null +++ b/exercises/01_variables/README.md @@ -0,0 +1,9 @@ +# 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. +You can make them mutable by adding `mut` in front of the variable name. + +## Further information + +- [Variables and Mutability](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html) diff --git a/exercises/01_variables/variables1.rs b/exercises/01_variables/variables1.rs new file mode 100644 index 0000000..b3e089a --- /dev/null +++ b/exercises/01_variables/variables1.rs @@ -0,0 +1,13 @@ +// variables1.rs +// +// Make me compile! +// +// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + x = 5; + println!("x has the value {}", x); +} diff --git a/exercises/01_variables/variables2.rs b/exercises/01_variables/variables2.rs new file mode 100644 index 0000000..e1c23ed --- /dev/null +++ b/exercises/01_variables/variables2.rs @@ -0,0 +1,15 @@ +// variables2.rs +// +// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + let x; + if x == 10 { + println!("x is ten!"); + } else { + println!("x is not ten!"); + } +} diff --git a/exercises/01_variables/variables3.rs b/exercises/01_variables/variables3.rs new file mode 100644 index 0000000..86bed41 --- /dev/null +++ b/exercises/01_variables/variables3.rs @@ -0,0 +1,11 @@ +// variables3.rs +// +// Execute `rustlings hint variables3` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + let x: i32; + println!("Number {}", x); +} diff --git a/exercises/01_variables/variables4.rs b/exercises/01_variables/variables4.rs new file mode 100644 index 0000000..5394f39 --- /dev/null +++ b/exercises/01_variables/variables4.rs @@ -0,0 +1,13 @@ +// variables4.rs +// +// Execute `rustlings hint variables4` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + let x = 3; + println!("Number {}", x); + x = 5; // don't change this line + println!("Number {}", x); +} diff --git a/exercises/01_variables/variables5.rs b/exercises/01_variables/variables5.rs new file mode 100644 index 0000000..a29b38b --- /dev/null +++ b/exercises/01_variables/variables5.rs @@ -0,0 +1,13 @@ +// 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 + println!("Number plus two is : {}", number + 2); +} diff --git a/exercises/01_variables/variables6.rs b/exercises/01_variables/variables6.rs new file mode 100644 index 0000000..853183b --- /dev/null +++ b/exercises/01_variables/variables6.rs @@ -0,0 +1,11 @@ +// variables6.rs +// +// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +const NUMBER = 3; +fn main() { + println!("Number {}", NUMBER); +} diff --git a/exercises/02_functions/README.md b/exercises/02_functions/README.md new file mode 100644 index 0000000..6662d0d --- /dev/null +++ b/exercises/02_functions/README.md @@ -0,0 +1,8 @@ +# Functions + +Here, you'll learn how to write functions and how the Rust compiler can help you debug errors even +in more complex code. + +## Further information + +- [How Functions Work](https://doc.rust-lang.org/book/ch03-03-how-functions-work.html) diff --git a/exercises/02_functions/functions1.rs b/exercises/02_functions/functions1.rs new file mode 100644 index 0000000..40ed9a0 --- /dev/null +++ b/exercises/02_functions/functions1.rs @@ -0,0 +1,10 @@ +// functions1.rs +// +// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + call_me(); +} diff --git a/exercises/02_functions/functions2.rs b/exercises/02_functions/functions2.rs new file mode 100644 index 0000000..5154f34 --- /dev/null +++ b/exercises/02_functions/functions2.rs @@ -0,0 +1,16 @@ +// 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:) { + 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 new file mode 100644 index 0000000..74f44d6 --- /dev/null +++ b/exercises/02_functions/functions3.rs @@ -0,0 +1,16 @@ +// functions3.rs +// +// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + call_me(); +} + +fn call_me(num: u32) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} diff --git a/exercises/02_functions/functions4.rs b/exercises/02_functions/functions4.rs new file mode 100644 index 0000000..77c4b2a --- /dev/null +++ b/exercises/02_functions/functions4.rs @@ -0,0 +1,28 @@ +// functions4.rs +// +// This store is having a sale where if the price is an even number, you get 10 +// Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. (Don't worry +// about the function bodies themselves, we're only interested in the signatures +// for now. If anything, this is a good way to peek ahead to future exercises!) +// +// Execute `rustlings hint functions4` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn main() { + let original_price = 51; + println!("Your sale price is {}", sale_price(original_price)); +} + +fn sale_price(price: i32) -> { + if is_even(price) { + price - 10 + } else { + price - 3 + } +} + +fn is_even(num: i32) -> bool { + num % 2 == 0 +} diff --git a/exercises/02_functions/functions5.rs b/exercises/02_functions/functions5.rs new file mode 100644 index 0000000..f1b63f4 --- /dev/null +++ b/exercises/02_functions/functions5.rs @@ -0,0 +1,15 @@ +// 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; +} diff --git a/exercises/03_if/README.md b/exercises/03_if/README.md new file mode 100644 index 0000000..b52c392 --- /dev/null +++ b/exercises/03_if/README.md @@ -0,0 +1,7 @@ +# If + +`if`, the most basic (but still surprisingly versatile!) type of control flow, is what you'll learn here. + +## Further information + +- [Control Flow - if expressions](https://doc.rust-lang.org/book/ch03-05-control-flow.html#if-expressions) diff --git a/exercises/03_if/if1.rs b/exercises/03_if/if1.rs new file mode 100644 index 0000000..4734d78 --- /dev/null +++ b/exercises/03_if/if1.rs @@ -0,0 +1,33 @@ +// 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 +} + +// Don't mind this for now :) +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ten_is_bigger_than_eight() { + assert_eq!(10, bigger(10, 8)); + } + + #[test] + fn fortytwo_is_bigger_than_thirtytwo() { + assert_eq!(42, bigger(32, 42)); + } + + #[test] + fn equal_numbers() { + assert_eq!(42, bigger(42, 42)); + } +} diff --git a/exercises/03_if/if2.rs b/exercises/03_if/if2.rs new file mode 100644 index 0000000..f512f13 --- /dev/null +++ b/exercises/03_if/if2.rs @@ -0,0 +1,37 @@ +// if2.rs +// +// Step 1: Make me compile! +// 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 { + 1 + } +} + +// No test changes needed! +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn foo_for_fizz() { + assert_eq!(foo_if_fizz("fizz"), "foo") + } + + #[test] + fn bar_for_fuzz() { + assert_eq!(foo_if_fizz("fuzz"), "bar") + } + + #[test] + fn default_to_baz() { + assert_eq!(foo_if_fizz("literally anything"), "baz") + } +} diff --git a/exercises/03_if/if3.rs b/exercises/03_if/if3.rs new file mode 100644 index 0000000..1696274 --- /dev/null +++ b/exercises/03_if/if3.rs @@ -0,0 +1,56 @@ +// if3.rs +// +// Execute `rustlings hint if3` or use the `hint` watch subcommand for a hint. + +// I AM NOT DONE + +pub fn animal_habitat(animal: &str) -> &'static str { + let identifier = if animal == "crab" { + 1 + } else if animal == "gopher" { + 2.0 + } else if animal == "snake" { + 3 + } else { + "Unknown" + }; + + // DO NOT CHANGE THIS STATEMENT BELOW + let habitat = if identifier == 1 { + "Beach" + } else if identifier == 2 { + "Burrow" + } else if identifier == 3 { + "Desert" + } else { + "Unknown" + }; + + habitat +} + +// No test changes needed. +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn gopher_lives_in_burrow() { + assert_eq!(animal_habitat("gopher"), "Burrow") + } + + #[test] + fn snake_lives_in_desert() { + assert_eq!(animal_habitat("snake"), "Desert") + } + + #[test] + fn crab_lives_on_beach() { + assert_eq!(animal_habitat("crab"), "Beach") + } + + #[test] + fn unknown_animal() { + assert_eq!(animal_habitat("dinosaur"), "Unknown") + } +} diff --git a/exercises/04_primitive_types/README.md b/exercises/04_primitive_types/README.md new file mode 100644 index 0000000..cea69b0 --- /dev/null +++ b/exercises/04_primitive_types/README.md @@ -0,0 +1,9 @@ +# Primitive Types + +Rust has a couple of basic types that are directly implemented into the +compiler. In this section, we'll go through the most important ones. + +## Further information + +- [Data Types](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html) +- [The Slice Type](https://doc.rust-lang.org/stable/book/ch04-03-slices.html) diff --git a/exercises/04_primitive_types/primitive_types1.rs b/exercises/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000..3663340 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types1.rs @@ -0,0 +1,20 @@ +// primitive_types1.rs +// +// 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`) + + let is_morning = true; + if is_morning { + println!("Good morning!"); + } + + let // Finish the rest of this line like the example! Or make it be false! + if is_evening { + println!("Good evening!"); + } +} diff --git a/exercises/04_primitive_types/primitive_types2.rs b/exercises/04_primitive_types/primitive_types2.rs new file mode 100644 index 0000000..f1616ed --- /dev/null +++ b/exercises/04_primitive_types/primitive_types2.rs @@ -0,0 +1,32 @@ +// primitive_types2.rs +// +// 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`) + + // Note the _single_ quotes, these are different from the double quotes + // you've been seeing around. + let my_first_initial = 'C'; + if my_first_initial.is_alphabetic() { + println!("Alphabetical!"); + } else if my_first_initial.is_numeric() { + println!("Numerical!"); + } else { + 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! + if your_character.is_alphabetic() { + println!("Alphabetical!"); + } else if your_character.is_numeric() { + println!("Numerical!"); + } else { + println!("Neither alphabetic nor numeric!"); + } +} diff --git a/exercises/04_primitive_types/primitive_types3.rs b/exercises/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000..8b0de44 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types3.rs @@ -0,0 +1,19 @@ +// primitive_types3.rs +// +// 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 = ??? + + if a.len() >= 100 { + println!("Wow, that's a big array!"); + } else { + println!("Meh, I eat arrays like that for breakfast."); + panic!("Array not big enough, more elements needed") + } +} diff --git a/exercises/04_primitive_types/primitive_types4.rs b/exercises/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000..d44d877 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types4.rs @@ -0,0 +1,17 @@ +// primitive_types4.rs +// +// 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 = ??? + + 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 new file mode 100644 index 0000000..f646986 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types5.rs @@ -0,0 +1,15 @@ +// primitive_types5.rs +// +// 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; + + println!("{} is {} years old.", name, age); +} diff --git a/exercises/04_primitive_types/primitive_types6.rs b/exercises/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000..07cc46c --- /dev/null +++ b/exercises/04_primitive_types/primitive_types6.rs @@ -0,0 +1,19 @@ +// primitive_types6.rs +// +// Use a tuple index to access the second element of `numbers`. 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 = ???; + + assert_eq!(2, second, + "This is not the 2nd number in the tuple!") +} diff --git a/exercises/05_vecs/README.md b/exercises/05_vecs/README.md new file mode 100644 index 0000000..8ff9b85 --- /dev/null +++ b/exercises/05_vecs/README.md @@ -0,0 +1,17 @@ +# Vectors + +Vectors are one of the most-used Rust data structures. In other programming +languages, they'd simply be called Arrays, but since Rust operates on a +bit of a lower level, an array in Rust is stored on the stack (meaning it +can't grow or shrink, and the size needs to be known at compile time), +and a Vector is stored in the heap (where these restrictions do not apply). + +Vectors are a bit of a later chapter in the book, but we think that they're +useful enough to talk about them a bit earlier. We shall be talking about +the other useful data structure, hash maps, later. + +## Further information + +- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html) +- [`iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut) +- [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map) diff --git a/exercises/05_vecs/vecs1.rs b/exercises/05_vecs/vecs1.rs new file mode 100644 index 0000000..65b7a7f --- /dev/null +++ b/exercises/05_vecs/vecs1.rs @@ -0,0 +1,28 @@ +// vecs1.rs +// +// Your task is to create a `Vec` which holds the exact same elements as in the +// array `a`. +// +// 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 + + (a, v) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_array_and_vec_similarity() { + let (a, v) = array_and_vec(); + assert_eq!(a, v[..]); + } +} diff --git a/exercises/05_vecs/vecs2.rs b/exercises/05_vecs/vecs2.rs new file mode 100644 index 0000000..e92c970 --- /dev/null +++ b/exercises/05_vecs/vecs2.rs @@ -0,0 +1,50 @@ +// vecs2.rs +// +// A Vec of even numbers is given. Your task is to complete the loop so that +// each number in the Vec is multiplied by 2. +// +// Make me pass the test! +// +// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint. + +// I AM NOT DONE + +fn vec_loop(mut v: Vec) -> Vec { + for element in v.iter_mut() { + // TODO: Fill this up so that each element in the Vec `v` is + // multiplied by 2. + ??? + } + + // At this point, `v` should be equal to [4, 8, 12, 16, 20]. + v +} + +fn vec_map(v: &Vec) -> Vec { + v.iter().map(|element| { + // TODO: Do the same thing as above - but instead of mutating the + // Vec, you can just return the new number! + ??? + }).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec_loop() { + let v: Vec = (1..).filter(|x| x % 2 == 0).take(5).collect(); + let ans = vec_loop(v.clone()); + + assert_eq!(ans, v.iter().map(|x| x * 2).collect::>()); + } + + #[test] + fn test_vec_map() { + let v: Vec = (1..).filter(|x| x % 2 == 0).take(5).collect(); + let ans = vec_map(&v); + + assert_eq!(ans, v.iter().map(|x| x * 2).collect::>()); + } +} diff --git a/exercises/06_move_semantics/README.md b/exercises/06_move_semantics/README.md new file mode 100644 index 0000000..54ddd8e --- /dev/null +++ b/exercises/06_move_semantics/README.md @@ -0,0 +1,10 @@ +# Move Semantics + +These exercises are adapted from [pnkfelix](https://github.com/pnkfelix)'s [Rust Tutorial](https://pnkfelix.github.io/rust-examples-icfp2014/) -- Thank you Felix!!! + +## Further information + +For this section, the book links are especially important. + +- [Ownership](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html) +- [Reference and borrowing](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html) diff --git a/exercises/06_move_semantics/move_semantics1.rs b/exercises/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000..e063937 --- /dev/null +++ b/exercises/06_move_semantics/move_semantics1.rs @@ -0,0 +1,23 @@ +// move_semantics1.rs +// +// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand +// for a hint. + +// I AM NOT DONE + +#[test] +fn main() { + let vec0 = vec![22, 44, 66]; + + let vec1 = fill_vec(vec0); + + assert_eq!(vec1, vec![22, 44, 66, 88]); +} + +fn fill_vec(vec: Vec) -> Vec { + let vec = vec; + + vec.push(88); + + vec +} diff --git a/exercises/06_move_semantics/move_semantics2.rs b/exercises/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000..baf6bcc --- /dev/null +++ b/exercises/06_move_semantics/move_semantics2.rs @@ -0,0 +1,26 @@ +// move_semantics2.rs +// +// Make the test pass by finding a way to keep both Vecs separate! +// +// Execute `rustlings hint move_semantics2` or use the `hint` watch subcommand +// for a hint. + +// I AM NOT DONE + +#[test] +fn main() { + let vec0 = vec![22, 44, 66]; + + let mut vec1 = fill_vec(vec0); + + assert_eq!(vec0, vec![22, 44, 66]); + assert_eq!(vec1, vec![22, 44, 66, 88]); +} + +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + + vec.push(88); + + vec +} diff --git a/exercises/06_move_semantics/move_semantics3.rs b/exercises/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000..7af9e69 --- /dev/null +++ b/exercises/06_move_semantics/move_semantics3.rs @@ -0,0 +1,24 @@ +// move_semantics3.rs +// +// Make me compile without adding new lines -- just changing existing lines! (no +// lines with multiple semicolons necessary!) +// +// Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand +// for a hint. + +// I AM NOT DONE + +#[test] +fn main() { + let vec0 = vec![22, 44, 66]; + + let mut vec1 = fill_vec(vec0); + + assert_eq!(vec1, vec![22, 44, 66, 88]); +} + +fn fill_vec(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 new file mode 100644 index 0000000..80b49db --- /dev/null +++ b/exercises/06_move_semantics/move_semantics4.rs @@ -0,0 +1,29 @@ +// move_semantics4.rs +// +// Refactor this code so that instead of passing `vec0` into the `fill_vec` +// function, the Vector gets created in the function itself and passed back to +// the main function. +// +// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand +// for a hint. + +// I AM NOT DONE + +#[test] +fn main() { + let vec0 = vec![22, 44, 66]; + + let mut vec1 = fill_vec(vec0); + + assert_eq!(vec1, vec![22, 44, 66, 88]); +} + +// `fill_vec()` no longer takes `vec: Vec` as argument - don't change this! +fn fill_vec() -> Vec { + // Instead, let's create and fill the Vec in here - how do you do that? + let mut vec = vec; + + vec.push(88); + + vec +} diff --git a/exercises/06_move_semantics/move_semantics5.rs b/exercises/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000..267bdcc --- /dev/null +++ b/exercises/06_move_semantics/move_semantics5.rs @@ -0,0 +1,19 @@ +// move_semantics5.rs +// +// Make me compile only by reordering the lines in `main()`, but without 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 + +#[test] +fn main() { + let mut x = 100; + let y = &mut x; + let z = &mut x; + *y += 100; + *z += 1000; + assert_eq!(x, 1200); +} diff --git a/exercises/06_move_semantics/move_semantics6.rs b/exercises/06_move_semantics/move_semantics6.rs new file mode 100644 index 0000000..cace4ca --- /dev/null +++ b/exercises/06_move_semantics/move_semantics6.rs @@ -0,0 +1,28 @@ +// move_semantics6.rs +// +// You can't change anything except adding or removing references. +// +// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand +// for a hint. + +// I AM NOT DONE + +fn main() { + let data = "Rust is great!".to_string(); + + get_char(data); + + string_uppercase(&data); +} + +// Should not take ownership +fn get_char(data: String) -> char { + data.chars().last().unwrap() +} + +// Should take ownership +fn string_uppercase(mut data: &String) { + data = &data.to_uppercase(); + + println!("{}", data); +} diff --git a/exercises/07_structs/README.md b/exercises/07_structs/README.md new file mode 100644 index 0000000..3fc1fdc --- /dev/null +++ b/exercises/07_structs/README.md @@ -0,0 +1,8 @@ +# Structs + +Rust has three struct types: a classic C struct, a tuple struct, and a unit struct. + +## Further information + +- [Structures](https://doc.rust-lang.org/book/ch05-01-defining-structs.html) +- [Method Syntax](https://doc.rust-lang.org/book/ch05-03-method-syntax.html) diff --git a/exercises/07_structs/structs1.rs b/exercises/07_structs/structs1.rs new file mode 100644 index 0000000..5fa5821 --- /dev/null +++ b/exercises/07_structs/structs1.rs @@ -0,0 +1,51 @@ +// structs1.rs +// +// 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 +} + +struct ColorTupleStruct(/* TODO: Something goes here */); + +#[derive(Debug)] +struct UnitLikeStruct; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classic_c_structs() { + // TODO: Instantiate a classic c struct! + // let green = + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + // TODO: Instantiate a tuple struct! + // let green = + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + // TODO: Instantiate a unit-like struct! + // let unit_like_struct = + let message = format!("{:?}s are fun!", unit_like_struct); + + assert_eq!(message, "UnitLikeStructs are fun!"); + } +} diff --git a/exercises/07_structs/structs2.rs b/exercises/07_structs/structs2.rs new file mode 100644 index 0000000..328567f --- /dev/null +++ b/exercises/07_structs/structs2.rs @@ -0,0 +1,50 @@ +// structs2.rs +// +// 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, + year: u32, + made_by_phone: bool, + made_by_mobile: bool, + made_by_email: bool, + item_number: u32, + count: u32, +} + +fn create_order_template() -> Order { + Order { + name: String::from("Bob"), + year: 2019, + made_by_phone: false, + made_by_mobile: false, + made_by_email: true, + item_number: 123, + count: 0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn your_order() { + let order_template = create_order_template(); + // TODO: Create your own order using the update syntax and template above! + // let your_order = + 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); + assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile); + assert_eq!(your_order.made_by_email, order_template.made_by_email); + assert_eq!(your_order.item_number, order_template.item_number); + assert_eq!(your_order.count, 1); + } +} diff --git a/exercises/07_structs/structs3.rs b/exercises/07_structs/structs3.rs new file mode 100644 index 0000000..7cda5af --- /dev/null +++ b/exercises/07_structs/structs3.rs @@ -0,0 +1,88 @@ +// structs3.rs +// +// Structs contain data, but can also have logic. In this exercise we have +// defined the Package struct and we want to test some logic attached to it. +// 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, + recipient_country: String, + weight_in_grams: u32, +} + +impl Package { + fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Package { + if weight_in_grams < 10 { + // This is not how you should handle errors in Rust, + // but we will learn about error handling later. + panic!("Can not ship a package with weight below 10 grams.") + } else { + Package { + sender_country, + recipient_country, + weight_in_grams, + } + } + } + + fn is_international(&self) -> ??? { + // Something goes here... + } + + fn get_fees(&self, cents_per_gram: u32) -> ??? { + // Something goes here... + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[should_panic] + fn fail_creating_weightless_package() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Austria"); + + Package::new(sender_country, recipient_country, 5); + } + + #[test] + fn create_international_package() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Russia"); + + let package = Package::new(sender_country, recipient_country, 1200); + + assert!(package.is_international()); + } + + #[test] + fn create_local_package() { + let sender_country = String::from("Canada"); + let recipient_country = sender_country.clone(); + + let package = Package::new(sender_country, recipient_country, 1200); + + assert!(!package.is_international()); + } + + #[test] + fn calculate_transport_fees() { + let sender_country = String::from("Spain"); + let recipient_country = String::from("Spain"); + + let cents_per_gram = 3; + + let package = Package::new(sender_country, recipient_country, 1500); + + assert_eq!(package.get_fees(cents_per_gram), 4500); + assert_eq!(package.get_fees(cents_per_gram * 2), 9000); + } +} diff --git a/exercises/08_enums/README.md b/exercises/08_enums/README.md new file mode 100644 index 0000000..30d4d91 --- /dev/null +++ b/exercises/08_enums/README.md @@ -0,0 +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. +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/ch18-03-pattern-syntax.html) diff --git a/exercises/08_enums/enums1.rs b/exercises/08_enums/enums1.rs new file mode 100644 index 0000000..25525b2 --- /dev/null +++ b/exercises/08_enums/enums1.rs @@ -0,0 +1,17 @@ +// enums1.rs +// +// No hints this time! ;) + +// I AM NOT DONE + +#[derive(Debug)] +enum Message { + // TODO: define a few types of messages as used below +} + +fn main() { + println!("{:?}", Message::Quit); + println!("{:?}", Message::Echo); + println!("{:?}", Message::Move); + println!("{:?}", Message::ChangeColor); +} diff --git a/exercises/08_enums/enums2.rs b/exercises/08_enums/enums2.rs new file mode 100644 index 0000000..df93fe0 --- /dev/null +++ b/exercises/08_enums/enums2.rs @@ -0,0 +1,30 @@ +// 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 +} + +impl Message { + fn call(&self) { + println!("{:?}", self); + } +} + +fn main() { + let messages = [ + Message::Move { x: 10, y: 30 }, + Message::Echo(String::from("hello world")), + Message::ChangeColor(200, 255, 255), + Message::Quit, + ]; + + for message in &messages { + message.call(); + } +} diff --git a/exercises/08_enums/enums3.rs b/exercises/08_enums/enums3.rs new file mode 100644 index 0000000..92d18c4 --- /dev/null +++ b/exercises/08_enums/enums3.rs @@ -0,0 +1,73 @@ +// enums3.rs +// +// 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 +} + +struct Point { + x: u8, + y: u8, +} + +struct State { + color: (u8, u8, u8), + position: Point, + quit: bool, + message: String, +} + +impl State { + fn change_color(&mut self, color: (u8, u8, u8)) { + self.color = color; + } + + fn quit(&mut self) { + self.quit = true; + } + + fn echo(&mut self, s: String) { + self.message = s + } + + fn move_position(&mut self, p: Point) { + self.position = p; + } + + fn process(&mut self, message: Message) { + // TODO: create a match expression to process the different message variants + // Remember: When passing a tuple as a function argument, you'll need extra parentheses: + // fn function((t, u, p, l, e)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_match_message_call() { + let mut state = State { + quit: false, + position: Point { x: 0, y: 0 }, + color: (0, 0, 0), + message: "hello world".to_string(), + }; + state.process(Message::ChangeColor(255, 0, 255)); + state.process(Message::Echo(String::from("Hello world!"))); + state.process(Message::Move(Point { x: 10, y: 15 })); + state.process(Message::Quit); + + assert_eq!(state.color, (255, 0, 255)); + assert_eq!(state.position.x, 10); + assert_eq!(state.position.y, 15); + assert_eq!(state.quit, true); + assert_eq!(state.message, "Hello world!"); + } +} diff --git a/exercises/09_strings/README.md b/exercises/09_strings/README.md new file mode 100644 index 0000000..fa2104c --- /dev/null +++ b/exercises/09_strings/README.md @@ -0,0 +1,9 @@ +# Strings + +Rust has two string types, a string slice (`&str`) and an owned string (`String`). +We're not going to dictate when you should use which one, but we'll show you how +to identify and create them, as well as use them. + +## Further information + +- [Strings](https://doc.rust-lang.org/book/ch08-02-strings.html) diff --git a/exercises/09_strings/strings1.rs b/exercises/09_strings/strings1.rs new file mode 100644 index 0000000..f50e1fa --- /dev/null +++ b/exercises/09_strings/strings1.rs @@ -0,0 +1,17 @@ +// strings1.rs +// +// 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" +} diff --git a/exercises/09_strings/strings2.rs b/exercises/09_strings/strings2.rs new file mode 100644 index 0000000..4d95d16 --- /dev/null +++ b/exercises/09_strings/strings2.rs @@ -0,0 +1,21 @@ +// strings2.rs +// +// 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) { + println!("That is a color word I know!"); + } else { + println!("That is not a color word I know."); + } +} + +fn is_a_color_word(attempt: &str) -> bool { + attempt == "green" || attempt == "blue" || attempt == "red" +} diff --git a/exercises/09_strings/strings3.rs b/exercises/09_strings/strings3.rs new file mode 100644 index 0000000..b29f932 --- /dev/null +++ b/exercises/09_strings/strings3.rs @@ -0,0 +1,45 @@ +// 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! + ??? +} + +fn compose_me(input: &str) -> String { + // TODO: Add " world!" to the string! There's multiple ways to do this! + ??? +} + +fn replace_me(input: &str) -> String { + // TODO: Replace "cars" in the string with "balloons"! + ??? +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn trim_a_string() { + assert_eq!(trim_me("Hello! "), "Hello!"); + assert_eq!(trim_me(" What's up!"), "What's up!"); + assert_eq!(trim_me(" Hola! "), "Hola!"); + } + + #[test] + fn compose_a_string() { + assert_eq!(compose_me("Hello"), "Hello world!"); + assert_eq!(compose_me("Goodbye"), "Goodbye world!"); + } + + #[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"); + } +} diff --git a/exercises/09_strings/strings4.rs b/exercises/09_strings/strings4.rs new file mode 100644 index 0000000..e8c54ac --- /dev/null +++ b/exercises/09_strings/strings4.rs @@ -0,0 +1,30 @@ +// strings4.rs +// +// Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your +// task is to call one of these two functions on each value depending on what +// you think each value is. That is, add either `string_slice` or `string` +// before the parentheses on each line. If you're right, it will compile! +// +// No hints this time! + +// I AM NOT DONE + +fn string_slice(arg: &str) { + println!("{}", arg); +} +fn string(arg: String) { + println!("{}", arg); +} + +fn main() { + ???("blue"); + ???("red".to_string()); + ???(String::from("hi")); + ???("rust is fun!".to_owned()); + ???("nice weather".into()); + ???(format!("Interpolation {}", "Station")); + ???(&String::from("abc")[0..1]); + ???(" hello there ".trim()); + ???("Happy Monday!".to_string().replace("Mon", "Tues")); + ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); +} diff --git a/exercises/10_modules/README.md b/exercises/10_modules/README.md new file mode 100644 index 0000000..3dc8a48 --- /dev/null +++ b/exercises/10_modules/README.md @@ -0,0 +1,7 @@ +# Modules + +In this section we'll give you an introduction to Rust's module system. + +## Further information + +- [The Module System](https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) diff --git a/exercises/10_modules/modules1.rs b/exercises/10_modules/modules1.rs new file mode 100644 index 0000000..9eb5a48 --- /dev/null +++ b/exercises/10_modules/modules1.rs @@ -0,0 +1,22 @@ +// 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() { + get_secret_recipe(); + println!("sausage!"); + } +} + +fn main() { + sausage_factory::make_sausage(); +} diff --git a/exercises/10_modules/modules2.rs b/exercises/10_modules/modules2.rs new file mode 100644 index 0000000..0415454 --- /dev/null +++ b/exercises/10_modules/modules2.rs @@ -0,0 +1,34 @@ +// modules2.rs +// +// You can bring module paths into scopes and provide new names for them with +// the '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 ??? + + mod fruits { + pub const PEAR: &'static str = "Pear"; + pub const APPLE: &'static str = "Apple"; + } + + mod veggies { + pub const CUCUMBER: &'static str = "Cucumber"; + pub const CARROT: &'static str = "Carrot"; + } +} + +fn main() { + println!( + "favorite snacks: {} and {}", + delicious_snacks::fruit, + delicious_snacks::veggie + ); +} diff --git a/exercises/10_modules/modules3.rs b/exercises/10_modules/modules3.rs new file mode 100644 index 0000000..f2bb050 --- /dev/null +++ b/exercises/10_modules/modules3.rs @@ -0,0 +1,21 @@ +// modules3.rs +// +// You can use the 'use' keyword to bring module paths from modules from +// anywhere and especially from the Rust standard library into your scope. Bring +// SystemTime and UNIX_EPOCH 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 ??? + +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/README.md b/exercises/11_hashmaps/README.md new file mode 100644 index 0000000..80ec144 --- /dev/null +++ b/exercises/11_hashmaps/README.md @@ -0,0 +1,12 @@ +# Hashmaps + +A *hash map* allows you to associate a value with a particular key. +You may also know this by the names [*unordered map* in C++](https://en.cppreference.com/w/cpp/container/unordered_map), +[*dictionary* in Python](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) or an *associative array* in other languages. + +This is the other data structure that we've been talking about before, when +talking about Vecs. + +## Further information + +- [Storing Keys with Associated Values in Hash Maps](https://doc.rust-lang.org/book/ch08-03-hash-maps.html) diff --git a/exercises/11_hashmaps/hashmaps1.rs b/exercises/11_hashmaps/hashmaps1.rs new file mode 100644 index 0000000..80829ea --- /dev/null +++ b/exercises/11_hashmaps/hashmaps1.rs @@ -0,0 +1,44 @@ +// hashmaps1.rs +// +// A basket of fruits in the form of a hash map needs to be defined. The key +// represents the name of the fruit and the value represents how many of that +// particular fruit is in the basket. You have to put at least three different +// types of fruits (e.g apple, banana, mango) in the basket and the total count +// of all the fruits should be at least five. +// +// Make me compile and pass the tests! +// +// 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. + + // Two bananas are already given for you :) + basket.insert(String::from("banana"), 2); + + // TODO: Put more fruits in your basket here. + + basket +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn at_least_three_types_of_fruits() { + let basket = fruit_basket(); + assert!(basket.len() >= 3); + } + + #[test] + fn at_least_five_fruits() { + let basket = fruit_basket(); + assert!(basket.values().sum::() >= 5); + } +} diff --git a/exercises/11_hashmaps/hashmaps2.rs b/exercises/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000..a592569 --- /dev/null +++ b/exercises/11_hashmaps/hashmaps2.rs @@ -0,0 +1,93 @@ +// hashmaps2.rs +// +// We're collecting different fruits to bake a delicious fruit cake. For this, +// we have a basket, which we'll represent in the form of a hash map. The key +// represents the name of each fruit we collect and the value represents how +// many of that particular fruit we have collected. Three types of fruits - +// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You +// must add fruit to the basket so that there is at least one of each kind and +// more than 11 in total - we have a lot of mouths to feed. You are not allowed +// to insert any more of these fruits! +// +// Make me pass the tests! +// +// 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)] +enum Fruit { + Apple, + Banana, + Mango, + Lychee, + Pineapple, +} + +fn fruit_basket(basket: &mut HashMap) { + let fruit_kinds = vec![ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + for fruit in fruit_kinds { + // TODO: Insert new fruits if they are not already present in the + // basket. Note that you are not allowed to put any type of fruit that's + // already present! + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Don't modify this function! + fn get_fruit_basket() -> HashMap { + let mut basket = HashMap::::new(); + basket.insert(Fruit::Apple, 4); + basket.insert(Fruit::Mango, 2); + basket.insert(Fruit::Lychee, 5); + + basket + } + + #[test] + fn test_given_fruits_are_not_modified() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4); + assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2); + assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5); + } + + #[test] + fn at_least_five_types_of_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count_fruit_kinds = basket.len(); + assert!(count_fruit_kinds >= 5); + } + + #[test] + fn greater_than_eleven_fruits() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + let count = basket.values().sum::(); + assert!(count > 11); + } + + #[test] + fn all_fruit_types_in_basket() { + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + for amount in basket.values() { + assert_ne!(amount, &0); + } + } +} diff --git a/exercises/11_hashmaps/hashmaps3.rs b/exercises/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000..08e977c --- /dev/null +++ b/exercises/11_hashmaps/hashmaps3.rs @@ -0,0 +1,86 @@ +// hashmaps3.rs +// +// A list of scores (one per line) of a soccer match is given. Each line is of +// the form : ",,," +// Example: England,France,4,2 (England scored 4 goals, France 2). +// +// You have to build a scores table containing the name of the team, goals the +// team scored, and goals the team conceded. One approach to build the scores +// table is to use a Hashmap. The solution is partially written to use a +// Hashmap, complete it to pass the test. +// +// Make me pass the tests! +// +// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +use std::collections::HashMap; + +// A structure to store the goal details of a team. +struct Team { + goals_scored: u8, + goals_conceded: u8, +} + +fn build_scores_table(results: String) -> HashMap { + // The name of the team is the key and its associated struct is the value. + let mut scores: HashMap = HashMap::new(); + + for r in results.lines() { + let v: Vec<&str> = r.split(',').collect(); + let team_1_name = v[0].to_string(); + let team_1_score: u8 = v[2].parse().unwrap(); + let team_2_name = v[1].to_string(); + let team_2_score: u8 = v[3].parse().unwrap(); + // TODO: Populate the scores table with details extracted from the + // current line. Keep in mind that goals scored by team_1 + // will be the number of goals conceded from team_2, and similarly + // goals scored by team_2 will be the number of goals conceded by + // team_1. + } + scores +} + +#[cfg(test)] +mod tests { + use super::*; + + fn get_results() -> String { + let results = "".to_string() + + "England,France,4,2\n" + + "France,Italy,3,1\n" + + "Poland,Spain,2,0\n" + + "Germany,England,2,1\n"; + results + } + + #[test] + fn build_scores() { + let scores = build_scores_table(get_results()); + + let mut keys: Vec<&String> = scores.keys().collect(); + keys.sort(); + assert_eq!( + keys, + vec!["England", "France", "Germany", "Italy", "Poland", "Spain"] + ); + } + + #[test] + fn validate_team_score_1() { + let scores = build_scores_table(get_results()); + let team = scores.get("England").unwrap(); + assert_eq!(team.goals_scored, 5); + assert_eq!(team.goals_conceded, 4); + } + + #[test] + fn validate_team_score_2() { + let scores = build_scores_table(get_results()); + let team = scores.get("Spain").unwrap(); + assert_eq!(team.goals_scored, 0); + assert_eq!(team.goals_conceded, 2); + } +} diff --git a/exercises/12_options/README.md b/exercises/12_options/README.md new file mode 100644 index 0000000..bdd3374 --- /dev/null +++ b/exercises/12_options/README.md @@ -0,0 +1,21 @@ +# Options + +Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. +Option types are very common in Rust code, as they have a number of uses: + +- Initial values +- Return values for functions that are not defined over their entire input range (partial functions) +- Return value for otherwise reporting simple errors, where None is returned on error +- Optional struct fields +- Struct fields that can be loaned or "taken" +- Optional function arguments +- Nullable pointers +- Swapping things out of difficult situations + +## Further Information + +- [Option Enum Format](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html#in-enum-definitions) +- [Option Module Documentation](https://doc.rust-lang.org/std/option/) +- [Option Enum Documentation](https://doc.rust-lang.org/std/option/enum.Option.html) +- [if let](https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html) +- [while let](https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html) diff --git a/exercises/12_options/options1.rs b/exercises/12_options/options1.rs new file mode 100644 index 0000000..e131b48 --- /dev/null +++ b/exercises/12_options/options1.rs @@ -0,0 +1,39 @@ +// 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 :( +fn maybe_icecream(time_of_day: u16) -> Option { + // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a + // value of 0 The Option output should gracefully handle cases where + // time_of_day > 23. + // TODO: Complete the function body - remember to return an Option! + ??? +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn check_icecream() { + assert_eq!(maybe_icecream(9), Some(5)); + assert_eq!(maybe_icecream(10), Some(5)); + assert_eq!(maybe_icecream(23), Some(0)); + assert_eq!(maybe_icecream(22), Some(0)); + assert_eq!(maybe_icecream(25), None); + } + + #[test] + fn raw_value() { + // TODO: Fix this test. How do you get at the value contained in the + // Option? + let icecreams = maybe_icecream(12); + assert_eq!(icecreams, 5); + } +} diff --git a/exercises/12_options/options2.rs b/exercises/12_options/options2.rs new file mode 100644 index 0000000..4d998e7 --- /dev/null +++ b/exercises/12_options/options2.rs @@ -0,0 +1,42 @@ +// options2.rs +// +// Execute `rustlings hint options2` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +#[cfg(test)] +mod tests { + #[test] + fn simple_option() { + let target = "rustlings"; + let optional_target = Some(target); + + // TODO: Make this an if let statement whose value is "Some" type + word = optional_target { + assert_eq!(word, target); + } + } + + #[test] + fn layered_option() { + let range = 10; + let mut optional_integers: Vec> = vec![None]; + + for i in 1..(range + 1) { + optional_integers.push(Some(i)); + } + + let mut cursor = range; + + // 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() { + assert_eq!(integer, cursor); + cursor -= 1; + } + + assert_eq!(cursor, 0); + } +} diff --git a/exercises/12_options/options3.rs b/exercises/12_options/options3.rs new file mode 100644 index 0000000..23c15ea --- /dev/null +++ b/exercises/12_options/options3.rs @@ -0,0 +1,21 @@ +// 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, +} + +fn main() { + let y: Option = Some(Point { x: 100, y: 200 }); + + match y { + Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), + _ => panic!("no match!"), + } + y; // Fix without deleting this line. +} diff --git a/exercises/13_error_handling/README.md b/exercises/13_error_handling/README.md new file mode 100644 index 0000000..3b21f2b --- /dev/null +++ b/exercises/13_error_handling/README.md @@ -0,0 +1,12 @@ +# 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. + +## Further information + +- [Error Handling](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html) +- [Generics](https://doc.rust-lang.org/book/ch10-01-syntax.html) +- [Result](https://doc.rust-lang.org/rust-by-example/error/result.html) +- [Boxing errors](https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/boxing_errors.html) diff --git a/exercises/13_error_handling/errors1.rs b/exercises/13_error_handling/errors1.rs new file mode 100644 index 0000000..0ba59a5 --- /dev/null +++ b/exercises/13_error_handling/errors1.rs @@ -0,0 +1,43 @@ +// errors1.rs +// +// This function refuses to generate text to be printed on a nametag if you pass +// it an empty string. It'd be nicer if it explained what the problem was, +// instead of just sometimes returning `None`. Thankfully, Rust has a similar +// 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 { + if name.is_empty() { + // Empty names aren't allowed. + None + } else { + Some(format!("Hi! My name is {}", name)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generates_nametag_text_for_a_nonempty_name() { + assert_eq!( + generate_nametag_text("Beyoncé".into()), + Ok("Hi! My name is Beyoncé".into()) + ); + } + + #[test] + fn explains_why_generating_nametag_text_fails() { + assert_eq!( + generate_nametag_text("".into()), + // Don't change this line + Err("`name` was empty; it must be nonempty.".into()) + ); + } +} diff --git a/exercises/13_error_handling/errors2.rs b/exercises/13_error_handling/errors2.rs new file mode 100644 index 0000000..631fe67 --- /dev/null +++ b/exercises/13_error_handling/errors2.rs @@ -0,0 +1,50 @@ +// errors2.rs +// +// Say we're writing a game where you can buy items with tokens. All items cost +// 5 tokens, and whenever you purchase items there is a processing fee of 1 +// token. A player of the game will type in how many items they want to buy, and +// the `total_cost` function will calculate the total cost of the items. Since +// the player typed in the quantity, though, we get it as a string-- and they +// might have typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all (and isn't +// handling the success case properly either). What we want to do is: if we call +// the `total_cost` function on a string that is not a number, that function +// will return a `ParseIntError`, and in that case, we want to immediately +// return that error from our function and not try to multiply and add. +// +// There are at least two ways to implement this that are both correct-- but 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::(); + + Ok(qty * cost_per_item + processing_fee) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn item_quantity_is_a_valid_number() { + assert_eq!(total_cost("34"), Ok(171)); + } + + #[test] + fn item_quantity_is_an_invalid_number() { + assert_eq!( + total_cost("beep boop").unwrap_err().to_string(), + "invalid digit found in string" + ); + } +} diff --git a/exercises/13_error_handling/errors3.rs b/exercises/13_error_handling/errors3.rs new file mode 100644 index 0000000..d42d3b1 --- /dev/null +++ b/exercises/13_error_handling/errors3.rs @@ -0,0 +1,34 @@ +// errors3.rs +// +// This is a program that is trying to use a completed version of the +// `total_cost` function from the previous exercise. It's not working though! +// 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() { + let mut tokens = 100; + let pretend_user_input = "8"; + + let cost = total_cost(pretend_user_input)?; + + if cost > tokens { + println!("You can't afford that many!"); + } else { + tokens -= cost; + println!("You now have {} tokens.", tokens); + } +} + +pub fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + let qty = item_quantity.parse::()?; + + Ok(qty * cost_per_item + processing_fee) +} diff --git a/exercises/13_error_handling/errors4.rs b/exercises/13_error_handling/errors4.rs new file mode 100644 index 0000000..d6d6fcb --- /dev/null +++ b/exercises/13_error_handling/errors4.rs @@ -0,0 +1,32 @@ +// 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); + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + // Hmm... Why is this always returning an Ok value? + Ok(PositiveNonzeroInteger(value as u64)) + } +} + +#[test] +fn test_creation() { + assert!(PositiveNonzeroInteger::new(10).is_ok()); + assert_eq!( + Err(CreationError::Negative), + PositiveNonzeroInteger::new(-10) + ); + assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0)); +} diff --git a/exercises/13_error_handling/errors5.rs b/exercises/13_error_handling/errors5.rs new file mode 100644 index 0000000..92461a7 --- /dev/null +++ b/exercises/13_error_handling/errors5.rs @@ -0,0 +1,71 @@ +// errors5.rs +// +// This program uses an altered version of the code from errors4. +// +// This exercise uses some concepts that we won't get to until later in the +// course, like `Box` and the `From` trait. It's not important to understand +// them in detail right now, but you can read ahead if you like. For now, think +// of the `Box` type as an "I want anything that does ???" type, which, +// given Rust's usual standards for runtime safety, should strike you as +// somewhat lenient! +// +// 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 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. +// +// What can we use to describe both errors? In other words, is there a trait +// which both errors implement? +// +// 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> { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} + +// Don't change anything below this line. + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + x if x == 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +// This is required so that `CreationError` can implement `error::Error`. +impl fmt::Display for CreationError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match *self { + CreationError::Negative => "number is negative", + CreationError::Zero => "number is zero", + }; + f.write_str(description) + } +} + +impl error::Error for CreationError {} diff --git a/exercises/13_error_handling/errors6.rs b/exercises/13_error_handling/errors6.rs new file mode 100644 index 0000000..aaf0948 --- /dev/null +++ b/exercises/13_error_handling/errors6.rs @@ -0,0 +1,94 @@ +// errors6.rs +// +// Using catch-all error types like `Box` isn't recommended +// for library code, where callers might want to make decisions based on the +// error content, instead of printing it out or propagating it further. Here, we +// define a custom error type to make it possible for callers to decide what to +// do next when our function returns an error. +// +// 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()`. +#[derive(PartialEq, Debug)] +enum ParsePosNonzeroError { + Creation(CreationError), + ParseInt(ParseIntError), +} + +impl ParsePosNonzeroError { + fn from_creation(err: CreationError) -> ParsePosNonzeroError { + ParsePosNonzeroError::Creation(err) + } + // TODO: add another error conversion function here. + // fn from_parseint... +} + +fn parse_pos_nonzero(s: &str) -> Result { + // TODO: change this to return an appropriate error instead of panicking + // when `parse()` returns an error. + let x: i64 = s.parse().unwrap(); + PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) +} + +// Don't change anything below this line. + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + x if x == 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_error() { + // We can't construct a ParseIntError, so we have to pattern match. + assert!(matches!( + parse_pos_nonzero("not a number"), + Err(ParsePosNonzeroError::ParseInt(_)) + )); + } + + #[test] + fn test_negative() { + assert_eq!( + parse_pos_nonzero("-555"), + Err(ParsePosNonzeroError::Creation(CreationError::Negative)) + ); + } + + #[test] + fn test_zero() { + assert_eq!( + parse_pos_nonzero("0"), + Err(ParsePosNonzeroError::Creation(CreationError::Zero)) + ); + } + + #[test] + fn test_positive() { + let x = PositiveNonzeroInteger::new(42); + assert!(x.is_ok()); + assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap())); + } +} diff --git a/exercises/14_generics/README.md b/exercises/14_generics/README.md new file mode 100644 index 0000000..de46d50 --- /dev/null +++ b/exercises/14_generics/README.md @@ -0,0 +1,11 @@ +# Generics + +Generics is the topic of generalizing types and functionalities to broader cases. +This is extremely useful for reducing code duplication in many ways, but can call for rather involving syntax. +Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid. +The simplest and most common use of generics is for type parameters. + +## Further information + +- [Generic Data Types](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html) +- [Bounds](https://doc.rust-lang.org/rust-by-example/generics/bounds.html) diff --git a/exercises/14_generics/generics1.rs b/exercises/14_generics/generics1.rs new file mode 100644 index 0000000..35c1d2f --- /dev/null +++ b/exercises/14_generics/generics1.rs @@ -0,0 +1,14 @@ +// generics1.rs +// +// This shopping list program isn't compiling! Use your knowledge of generics to +// fix it. +// +// 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(); + shopping_list.push("milk"); +} diff --git a/exercises/14_generics/generics2.rs b/exercises/14_generics/generics2.rs new file mode 100644 index 0000000..074cd93 --- /dev/null +++ b/exercises/14_generics/generics2.rs @@ -0,0 +1,34 @@ +// generics2.rs +// +// This powerful wrapper provides the ability to store a positive integer value. +// Rewrite it using generics so that it supports wrapping ANY type. +// +// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +struct Wrapper { + value: u32, +} + +impl Wrapper { + pub fn new(value: u32) -> Self { + Wrapper { value } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn store_u32_in_wrapper() { + assert_eq!(Wrapper::new(42).value, 42); + } + + #[test] + fn store_str_in_wrapper() { + assert_eq!(Wrapper::new("Foo").value, "Foo"); + } +} diff --git a/exercises/15_traits/README.md b/exercises/15_traits/README.md new file mode 100644 index 0000000..ac87c64 --- /dev/null +++ b/exercises/15_traits/README.md @@ -0,0 +1,19 @@ +# Traits + +A trait is a collection of methods. + +Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the `String` data type implements the `From<&str>` trait. This allows a user to write `String::from("hello")`. + +In this way, traits are somewhat similar to Java interfaces and C++ abstract classes. + +Some additional common Rust traits include: + +- `Clone` (the `clone` method) +- `Display` (which allows formatted display via `{}`) +- `Debug` (which allows formatted display via `{:?}`) + +Because traits indicate shared behavior between data types, they are useful when writing generics. + +## Further information + +- [Traits](https://doc.rust-lang.org/book/ch10-02-traits.html) diff --git a/exercises/15_traits/traits1.rs b/exercises/15_traits/traits1.rs new file mode 100644 index 0000000..37dfcbf --- /dev/null +++ b/exercises/15_traits/traits1.rs @@ -0,0 +1,42 @@ +// traits1.rs +// +// Time to implement some traits! Your task is to implement the trait +// `AppendBar` for the type `String`. The trait AppendBar has only one function, +// which appends "Bar" to any object 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 { + // TODO: Implement `AppendBar` for type `String`. +} + +fn main() { + let s = String::from("Foo"); + let s = s.append_bar(); + println!("s: {}", s); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_foo_bar() { + assert_eq!(String::from("Foo").append_bar(), String::from("FooBar")); + } + + #[test] + fn is_bar_bar() { + assert_eq!( + String::from("").append_bar().append_bar(), + String::from("BarBar") + ); + } +} diff --git a/exercises/15_traits/traits2.rs b/exercises/15_traits/traits2.rs new file mode 100644 index 0000000..3e35f8e --- /dev/null +++ b/exercises/15_traits/traits2.rs @@ -0,0 +1,29 @@ +// traits2.rs +// +// Your task is to implement the trait `AppendBar` for a vector of strings. To +// implement this trait, consider for a moment what it means to 'append "Bar"' +// to a vector of strings. +// +// No boiler plate code this time, 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: Implement trait `AppendBar` for a vector of strings. + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_vec_pop_eq_bar() { + let mut foo = vec![String::from("Foo")].append_bar(); + assert_eq!(foo.pop().unwrap(), String::from("Bar")); + assert_eq!(foo.pop().unwrap(), String::from("Foo")); + } +} diff --git a/exercises/15_traits/traits3.rs b/exercises/15_traits/traits3.rs new file mode 100644 index 0000000..4e2b06b --- /dev/null +++ b/exercises/15_traits/traits3.rs @@ -0,0 +1,42 @@ +// traits3.rs +// +// Your task is to implement the Licensed trait for both structures and have +// them return the same information without writing the same function twice. +// +// 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; +} + +struct SomeSoftware { + version_number: i32, +} + +struct OtherSoftware { + version_number: String, +} + +impl Licensed for SomeSoftware {} // Don't edit this line +impl Licensed for OtherSoftware {} // Don't edit this line + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_licensing_info_the_same() { + let licensing_info = String::from("Some information"); + let some_software = SomeSoftware { version_number: 1 }; + let other_software = OtherSoftware { + version_number: "v2.0.0".to_string(), + }; + assert_eq!(some_software.licensing_info(), licensing_info); + assert_eq!(other_software.licensing_info(), licensing_info); + } +} diff --git a/exercises/15_traits/traits4.rs b/exercises/15_traits/traits4.rs new file mode 100644 index 0000000..4bda3e5 --- /dev/null +++ b/exercises/15_traits/traits4.rs @@ -0,0 +1,49 @@ +// traits4.rs +// +// Your task is to replace the '??' sections so the code compiles. +// +// 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() + } +} + +struct SomeSoftware {} + +struct OtherSoftware {} + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +// YOU MAY ONLY CHANGE THE NEXT LINE +fn compare_license_types(software: ??, software_two: ??) -> bool { + software.licensing_info() == software_two.licensing_info() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compare_license_information() { + let some_software = SomeSoftware {}; + let other_software = OtherSoftware {}; + + assert!(compare_license_types(some_software, other_software)); + } + + #[test] + fn compare_license_information_backwards() { + let some_software = SomeSoftware {}; + let other_software = OtherSoftware {}; + + assert!(compare_license_types(other_software, some_software)); + } +} diff --git a/exercises/15_traits/traits5.rs b/exercises/15_traits/traits5.rs new file mode 100644 index 0000000..df18380 --- /dev/null +++ b/exercises/15_traits/traits5.rs @@ -0,0 +1,40 @@ +// traits5.rs +// +// Your task is to replace the '??' sections so the code compiles. +// +// 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 + } +} + +pub trait OtherTrait { + fn other_function(&self) -> bool { + true + } +} + +struct SomeStruct {} +struct OtherStruct {} + +impl SomeTrait for SomeStruct {} +impl OtherTrait for SomeStruct {} +impl SomeTrait for OtherStruct {} +impl OtherTrait for OtherStruct {} + +// YOU MAY ONLY CHANGE THE NEXT LINE +fn some_func(item: ??) -> bool { + item.some_function() && item.other_function() +} + +fn main() { + some_func(SomeStruct {}); + some_func(OtherStruct {}); +} diff --git a/exercises/16_lifetimes/README.md b/exercises/16_lifetimes/README.md new file mode 100644 index 0000000..91373f7 --- /dev/null +++ b/exercises/16_lifetimes/README.md @@ -0,0 +1,22 @@ +# Lifetimes + +Lifetimes tell the compiler how to check whether references live long +enough to be valid in any given situation. For example lifetimes say +"make sure parameter 'a' lives as long as parameter 'b' so that the return +value is valid". + +They are only necessary on borrows, i.e. references, +since copied parameters or moves are owned in their scope and cannot +be referenced outside. Lifetimes mean that calling code of e.g. functions +can be checked to make sure their arguments are valid. Lifetimes are +restrictive of their callers. + +If you'd like to learn more about lifetime annotations, the +[lifetimekata](https://tfpk.github.io/lifetimekata/) project +has a similar style of exercises to Rustlings, but is all about +learning to write lifetime annotations. + +## Further information + +- [Lifetimes (in Rust By Example)](https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime.html) +- [Validating References with Lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) diff --git a/exercises/16_lifetimes/lifetimes1.rs b/exercises/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000..87bde49 --- /dev/null +++ b/exercises/16_lifetimes/lifetimes1.rs @@ -0,0 +1,27 @@ +// lifetimes1.rs +// +// The Rust compiler needs to know how to check whether supplied references are +// valid, so that it can let the programmer know if a reference is at risk of +// going out of scope before it is used. Remember, references are borrows and do +// not own their own data. What if their owner goes out of scope? +// +// Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +fn longest(x: &str, y: &str) -> &str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + let string1 = String::from("abcd"); + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + println!("The longest string is '{}'", result); +} diff --git a/exercises/16_lifetimes/lifetimes2.rs b/exercises/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000..4f3d8c1 --- /dev/null +++ b/exercises/16_lifetimes/lifetimes2.rs @@ -0,0 +1,27 @@ +// lifetimes2.rs +// +// So if the compiler is just validating the references passed to the annotated +// parameters and the return type, what do we need to change? +// +// 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 + } else { + y + } +} + +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()); + } + println!("The longest string is '{}'", result); +} diff --git a/exercises/16_lifetimes/lifetimes3.rs b/exercises/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000..9c59f9c --- /dev/null +++ b/exercises/16_lifetimes/lifetimes3.rs @@ -0,0 +1,21 @@ +// lifetimes3.rs +// +// Lifetimes are also needed when structs hold references. +// +// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +struct Book { + author: &str, + title: &str, +} + +fn main() { + let name = String::from("Jill Smith"); + let title = String::from("Fish Flying"); + let book = Book { author: &name, title: &title }; + + println!("{} by {}", book.title, book.author); +} diff --git a/exercises/17_tests/README.md b/exercises/17_tests/README.md new file mode 100644 index 0000000..27c6818 --- /dev/null +++ b/exercises/17_tests/README.md @@ -0,0 +1,7 @@ +# Tests + +Going out of order from the book to cover tests -- many of the following exercises will ask you to make tests pass! + +## Further information + +- [Writing Tests](https://doc.rust-lang.org/book/ch11-01-writing-tests.html) diff --git a/exercises/17_tests/tests1.rs b/exercises/17_tests/tests1.rs new file mode 100644 index 0000000..810277a --- /dev/null +++ b/exercises/17_tests/tests1.rs @@ -0,0 +1,21 @@ +// tests1.rs +// +// Tests are important to ensure that your code does what you think it should +// do. Tests can be run on this file with the following command: rustlings run +// tests1 +// +// This test has a problem with it -- make the test compile! Make the test 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!(); + } +} diff --git a/exercises/17_tests/tests2.rs b/exercises/17_tests/tests2.rs new file mode 100644 index 0000000..f8024e9 --- /dev/null +++ b/exercises/17_tests/tests2.rs @@ -0,0 +1,17 @@ +// tests2.rs +// +// This test has a problem with it -- make the test compile! Make the test 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!(); + } +} diff --git a/exercises/17_tests/tests3.rs b/exercises/17_tests/tests3.rs new file mode 100644 index 0000000..4013e38 --- /dev/null +++ b/exercises/17_tests/tests3.rs @@ -0,0 +1,29 @@ +// tests3.rs +// +// This test isn't testing our function -- make it do that in such a way that +// the test passes. Then write a second test that tests whether we get the +// result 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 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_true_when_even() { + assert!(); + } + + #[test] + fn is_false_when_odd() { + assert!(); + } +} diff --git a/exercises/17_tests/tests4.rs b/exercises/17_tests/tests4.rs new file mode 100644 index 0000000..935d0db --- /dev/null +++ b/exercises/17_tests/tests4.rs @@ -0,0 +1,48 @@ +// tests4.rs +// +// Make sure that we're testing for the correct conditions! +// +// Execute `rustlings hint tests4` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +struct Rectangle { + width: i32, + height: i32 +} + +impl Rectangle { + // Only change the test functions themselves + pub fn new(width: i32, height: i32) -> Self { + if width <= 0 || height <= 0 { + panic!("Rectangle width and height cannot be negative!") + } + Rectangle {width, height} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correct_width_and_height() { + // This test should check if the rectangle is the size that we pass into its constructor + let rect = Rectangle::new(10, 20); + assert_eq!(???, 10); // check width + assert_eq!(???, 20); // check height + } + + #[test] + fn negative_width() { + // This test should check if program panics when we try to create rectangle with negative width + let _rect = Rectangle::new(-10, 10); + } + + #[test] + fn negative_height() { + // This test should check if program panics when we try to create rectangle with negative height + let _rect = Rectangle::new(10, -10); + } +} diff --git a/exercises/18_iterators/README.md b/exercises/18_iterators/README.md new file mode 100644 index 0000000..0e8b671 --- /dev/null +++ b/exercises/18_iterators/README.md @@ -0,0 +1,8 @@ +# Iterators + +This section will teach you about Iterators. + +## Further information + +- [Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) +- [Iterator documentation](https://doc.rust-lang.org/stable/std/iter/) diff --git a/exercises/18_iterators/iterators1.rs b/exercises/18_iterators/iterators1.rs new file mode 100644 index 0000000..31076bb --- /dev/null +++ b/exercises/18_iterators/iterators1.rs @@ -0,0 +1,26 @@ +// iterators1.rs +// +// When performing operations on elements within a collection, iterators are +// essential. This module helps you get familiar with the structure of using an +// iterator and how to go through elements within an iterable collection. +// +// Make me compile by filling in the `???`s +// +// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +#[test] +fn main() { + let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; + + let mut my_iterable_fav_fruits = ???; // 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(&"avocado")); + assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 + assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); + assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 +} diff --git a/exercises/18_iterators/iterators2.rs b/exercises/18_iterators/iterators2.rs new file mode 100644 index 0000000..dda82a0 --- /dev/null +++ b/exercises/18_iterators/iterators2.rs @@ -0,0 +1,63 @@ +// iterators2.rs +// +// In this exercise, you'll learn some of the unique advantages that iterators +// 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" +pub fn capitalize_first(input: &str) -> String { + let mut c = input.chars(); + match c.next() { + None => String::new(), + Some(first) => ???, + } +} + +// Step 2. +// Apply the `capitalize_first` function to a slice of string slices. +// Return a vector of strings. +// ["hello", "world"] -> ["Hello", "World"] +pub fn capitalize_words_vector(words: &[&str]) -> Vec { + vec![] +} + +// Step 3. +// Apply the `capitalize_first` function again to a slice of string slices. +// Return a single string. +// ["hello", " ", "world"] -> "Hello World" +pub fn capitalize_words_string(words: &[&str]) -> String { + String::new() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(capitalize_first("hello"), "Hello"); + } + + #[test] + fn test_empty() { + assert_eq!(capitalize_first(""), ""); + } + + #[test] + fn test_iterate_string_vec() { + let words = vec!["hello", "world"]; + assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]); + } + + #[test] + fn test_iterate_into_string() { + let words = vec!["hello", " ", "world"]; + assert_eq!(capitalize_words_string(&words), "Hello World"); + } +} diff --git a/exercises/18_iterators/iterators3.rs b/exercises/18_iterators/iterators3.rs new file mode 100644 index 0000000..29fa23a --- /dev/null +++ b/exercises/18_iterators/iterators3.rs @@ -0,0 +1,90 @@ +// iterators3.rs +// +// This is a bigger exercise than most of the others! You can do it! Here is +// your mission, should you choose to accept it: +// 1. Complete the divide function to get the first four tests to pass. +// 2. Get the remaining tests to pass by completing the result_with_list and +// 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), + DivideByZero, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct NotDivisibleError { + dividend: i32, + divisor: i32, +} + +// 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!(); +} + +// 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() -> () { + let numbers = vec![27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); +} + +// 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() -> () { + let numbers = vec![27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + } + + #[test] + fn test_not_divisible() { + assert_eq!( + divide(81, 6), + Err(DivisionError::NotDivisible(NotDivisibleError { + dividend: 81, + divisor: 6 + })) + ); + } + + #[test] + fn test_divide_by_0() { + assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); + } + + #[test] + fn test_divide_0_by_something() { + assert_eq!(divide(0, 81), Ok(0)); + } + + #[test] + fn test_result_with_list() { + assert_eq!(format!("{:?}", result_with_list()), "Ok([1, 11, 1426, 3])"); + } + + #[test] + fn test_list_of_results() { + assert_eq!( + format!("{:?}", list_of_results()), + "[Ok(1), Ok(11), Ok(1426), Ok(3)]" + ); + } +} diff --git a/exercises/18_iterators/iterators4.rs b/exercises/18_iterators/iterators4.rs new file mode 100644 index 0000000..79e1692 --- /dev/null +++ b/exercises/18_iterators/iterators4.rs @@ -0,0 +1,42 @@ +// 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: + // - return + // Try not to use: + // - imperative style loops (for, while) + // - additional variables + // For an extra challenge, don't use: + // - recursion + // Execute `rustlings hint iterators4` for hints. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factorial_of_0() { + assert_eq!(1, factorial(0)); + } + + #[test] + fn factorial_of_1() { + assert_eq!(1, factorial(1)); + } + #[test] + fn factorial_of_2() { + assert_eq!(2, factorial(2)); + } + + #[test] + fn factorial_of_4() { + assert_eq!(24, factorial(4)); + } +} diff --git a/exercises/18_iterators/iterators5.rs b/exercises/18_iterators/iterators5.rs new file mode 100644 index 0000000..a062ee4 --- /dev/null +++ b/exercises/18_iterators/iterators5.rs @@ -0,0 +1,156 @@ +// iterators5.rs +// +// Let's define a simple model to track Rustlings exercise progress. Progress +// will be modelled using a hash map. The name of the exercise is the key and +// the progress is the value. Two counting functions were created to count the +// number of exercises with a given progress. Recreate this counting +// functionality using iterators. Try not to use imperative loops (for, while). +// Only the two iterator methods (count_iterator and count_collection_iterator) +// need to be modified. +// +// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +use std::collections::HashMap; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Progress { + None, + Some, + Complete, +} + +fn count_for(map: &HashMap, value: Progress) -> usize { + let mut count = 0; + for val in map.values() { + if val == &value { + count += 1; + } + } + count +} + +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!(); +} + +fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { + let mut count = 0; + for map in collection { + for val in map.values() { + if val == &value { + count += 1; + } + } + } + count +} + +fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { + // collection is a slice of hashmaps. + // collection = [{ "variables1": Complete, "from_str": None, ... }, + // { "variables2": Complete, ... }, ... ] + todo!(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn count_complete() { + let map = get_map(); + assert_eq!(3, count_iterator(&map, Progress::Complete)); + } + + #[test] + fn count_some() { + let map = get_map(); + assert_eq!(1, count_iterator(&map, Progress::Some)); + } + + #[test] + fn count_none() { + let map = get_map(); + assert_eq!(2, count_iterator(&map, Progress::None)); + } + + #[test] + fn count_complete_equals_for() { + let map = get_map(); + let progress_states = vec![Progress::Complete, Progress::Some, Progress::None]; + for progress_state in progress_states { + assert_eq!( + count_for(&map, progress_state), + count_iterator(&map, progress_state) + ); + } + } + + #[test] + fn count_collection_complete() { + let collection = get_vec_map(); + assert_eq!( + 6, + count_collection_iterator(&collection, Progress::Complete) + ); + } + + #[test] + fn count_collection_some() { + let collection = get_vec_map(); + assert_eq!(1, count_collection_iterator(&collection, Progress::Some)); + } + + #[test] + fn count_collection_none() { + let collection = get_vec_map(); + assert_eq!(4, count_collection_iterator(&collection, Progress::None)); + } + + #[test] + fn count_collection_equals_for() { + let progress_states = vec![Progress::Complete, Progress::Some, Progress::None]; + let collection = get_vec_map(); + + for progress_state in progress_states { + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator(&collection, progress_state) + ); + } + } + + fn get_map() -> HashMap { + use Progress::*; + + let mut map = HashMap::new(); + map.insert(String::from("variables1"), Complete); + map.insert(String::from("functions1"), Complete); + map.insert(String::from("hashmap1"), Complete); + map.insert(String::from("arc1"), Some); + map.insert(String::from("as_ref_mut"), None); + map.insert(String::from("from_str"), None); + + map + } + + fn get_vec_map() -> Vec> { + use Progress::*; + + let map = get_map(); + + let mut other = HashMap::new(); + other.insert(String::from("variables2"), Complete); + other.insert(String::from("functions2"), Complete); + other.insert(String::from("if1"), Complete); + other.insert(String::from("from_into"), None); + other.insert(String::from("try_from_into"), None); + + vec![map, other] + } +} diff --git a/exercises/19_smart_pointers/README.md b/exercises/19_smart_pointers/README.md new file mode 100644 index 0000000..d56d2b6 --- /dev/null +++ b/exercises/19_smart_pointers/README.md @@ -0,0 +1,12 @@ +# Smart Pointers + +In Rust, smart pointers are variables that contain an address in memory and reference some other data, but they also have additional metadata and capabilities. +Smart pointers in Rust often own the data they point to, while references only borrow data. + +## Further Information + +- [Smart Pointers](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) +- [Using Box to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html) +- [Rc\, the Reference Counted Smart Pointer](https://doc.rust-lang.org/book/ch15-04-rc.html) +- [Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html) +- [Cow Documentation](https://doc.rust-lang.org/std/borrow/enum.Cow.html) diff --git a/exercises/19_smart_pointers/arc1.rs b/exercises/19_smart_pointers/arc1.rs new file mode 100644 index 0000000..3526ddc --- /dev/null +++ b/exercises/19_smart_pointers/arc1.rs @@ -0,0 +1,45 @@ +// arc1.rs +// +// In this exercise, we are given a Vec of u32 called "numbers" with values +// ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this +// set of numbers within 8 different threads simultaneously. Each thread is +// going to get the sum of every eighth value, with an offset. +// +// The first thread (offset 0), will sum 0, 8, 16, ... +// The second thread (offset 1), will sum 1, 9, 17, ... +// The third thread (offset 2), will sum 2, 10, 18, ... +// ... +// The eighth thread (offset 7), will sum 7, 15, 23, ... +// +// 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 mut joinhandles = Vec::new(); + + for offset in 0..8 { + let child_numbers = // 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); + })); + } + for handle in joinhandles.into_iter() { + handle.join().unwrap(); + } +} diff --git a/exercises/19_smart_pointers/box1.rs b/exercises/19_smart_pointers/box1.rs new file mode 100644 index 0000000..513e7da --- /dev/null +++ b/exercises/19_smart_pointers/box1.rs @@ -0,0 +1,58 @@ +// box1.rs +// +// At compile time, Rust needs to know how much space a type takes up. This +// becomes problematic for recursive types, where a value can have as part of +// itself another value of the same type. To get around the issue, we can use a +// `Box` - a smart pointer used to store data on the heap, which also allows us +// to wrap a recursive type. +// +// The recursive type we're implementing in this exercise is the `cons list` - a +// data structure frequently found in functional programming languages. Each +// item in a cons list contains two elements: the value of the current item and +// the next item. The last item is a value called `Nil`. +// +// Step 1: use a `Box` in the enum definition to make the code compile +// Step 2: create both empty and non-empty cons lists by replacing `todo!()` +// +// Note: the tests should not be changed +// +// 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), + Nil, +} + +fn main() { + println!("This is an empty cons list: {:?}", create_empty_list()); + println!( + "This is a non-empty cons list: {:?}", + create_non_empty_list() + ); +} + +pub fn create_empty_list() -> List { + todo!() +} + +pub fn create_non_empty_list() -> List { + todo!() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_empty_list() { + assert_eq!(List::Nil, create_empty_list()) + } + + #[test] + fn test_create_non_empty_list() { + assert_ne!(create_empty_list(), create_non_empty_list()) + } +} diff --git a/exercises/19_smart_pointers/cow1.rs b/exercises/19_smart_pointers/cow1.rs new file mode 100644 index 0000000..fcd3e0b --- /dev/null +++ b/exercises/19_smart_pointers/cow1.rs @@ -0,0 +1,78 @@ +// cow1.rs +// +// This exercise explores the Cow, or Clone-On-Write type. Cow is a +// clone-on-write smart pointer. 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. +// +// This exercise is meant to show you what to expect when passing data to Cow. +// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the +// TODO markers. +// +// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. + +// I AM NOT DONE + +use std::borrow::Cow; + +fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { + for i in 0..input.len() { + let v = input[i]; + if v < 0 { + // Clones into a vector if not already owned. + input.to_mut()[i] = -v; + } + } + input +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reference_mutation() -> Result<(), &'static str> { + // Clone occurs because `input` needs to be mutated. + let slice = [-1, 0, 1]; + let mut input = Cow::from(&slice[..]); + match abs_all(&mut input) { + Cow::Owned(_) => Ok(()), + _ => Err("Expected owned value"), + } + } + + #[test] + fn reference_no_mutation() -> Result<(), &'static str> { + // No clone occurs because `input` doesn't need to be mutated. + let slice = [0, 1, 2]; + let mut input = Cow::from(&slice[..]); + match abs_all(&mut input) { + // TODO + } + } + + #[test] + fn owned_no_mutation() -> Result<(), &'static str> { + // We can also pass `slice` without `&` so Cow owns it directly. In this + // case no mutation occurs and thus also no clone, but the result is + // still owned because it was never borrowed or mutated. + let slice = vec![0, 1, 2]; + let mut input = Cow::from(slice); + match abs_all(&mut input) { + // TODO + } + } + + #[test] + fn owned_mutation() -> Result<(), &'static str> { + // Of course this is also the case if a mutation does occur. In this + // case the call to `to_mut()` in the abs_all() function returns a + // reference to the same data as before. + let slice = vec![-1, 0, 1]; + let mut input = Cow::from(slice); + match abs_all(&mut input) { + // TODO + } + } +} diff --git a/exercises/19_smart_pointers/rc1.rs b/exercises/19_smart_pointers/rc1.rs new file mode 100644 index 0000000..1b90346 --- /dev/null +++ b/exercises/19_smart_pointers/rc1.rs @@ -0,0 +1,105 @@ +// rc1.rs +// +// In this exercise, we want to express the concept of multiple owners via the +// Rc type. This is a model of our solar system - there is a Sun type and +// multiple Planets. The Planets take ownership of the sun, indicating that they +// revolve around the sun. +// +// Make this code compile by using the proper Rc primitives to express that the +// sun has multiple owners. +// +// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. + +// I AM NOT DONE + +use std::rc::Rc; + +#[derive(Debug)] +struct Sun {} + +#[derive(Debug)] +enum Planet { + Mercury(Rc), + Venus(Rc), + Earth(Rc), + Mars(Rc), + Jupiter(Rc), + Saturn(Rc), + Uranus(Rc), + Neptune(Rc), +} + +impl Planet { + fn details(&self) { + println!("Hi from {:?}!", self) + } +} + +#[test] +fn main() { + let sun = Rc::new(Sun {}); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + let mercury = Planet::Mercury(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + mercury.details(); + + let venus = Planet::Venus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + venus.details(); + + let earth = Planet::Earth(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + earth.details(); + + let mars = Planet::Mars(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + mars.details(); + + let jupiter = Planet::Jupiter(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + jupiter.details(); + + // TODO + let saturn = Planet::Saturn(Rc::new(Sun {})); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + // TODO + let uranus = Planet::Uranus(Rc::new(Sun {})); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + // TODO + let neptune = Planet::Neptune(Rc::new(Sun {})); + println!("reference count = {}", Rc::strong_count(&sun)); // 9 references + neptune.details(); + + assert_eq!(Rc::strong_count(&sun), 9); + + drop(neptune); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + + drop(uranus); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + + drop(saturn); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + + drop(jupiter); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + + drop(mars); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + assert_eq!(Rc::strong_count(&sun), 1); +} diff --git a/exercises/20_threads/README.md b/exercises/20_threads/README.md new file mode 100644 index 0000000..dbe6664 --- /dev/null +++ b/exercises/20_threads/README.md @@ -0,0 +1,9 @@ +# Threads + +In most current operating systems, an executed program's code is run in a process, and the operating system manages multiple processes at once. +Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. + +## Further information + +- [Dining Philosophers example](https://doc.rust-lang.org/1.4.0/book/dining-philosophers.html) +- [Using Threads to Run Code Simultaneously](https://doc.rust-lang.org/book/ch16-01-threads.html) diff --git a/exercises/20_threads/threads1.rs b/exercises/20_threads/threads1.rs new file mode 100644 index 0000000..80b6def --- /dev/null +++ b/exercises/20_threads/threads1.rs @@ -0,0 +1,40 @@ +// threads1.rs +// +// This program spawns multiple threads that each run for at least 250ms, and +// each thread returns how much time they took to complete. The program should +// wait until all the spawned threads have finished and should collect their +// return values into a vector. +// +// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +use std::thread; +use std::time::{Duration, Instant}; + +fn main() { + let mut handles = vec![]; + for i in 0..10 { + handles.push(thread::spawn(move || { + let start = Instant::now(); + thread::sleep(Duration::from_millis(250)); + println!("thread {} is complete", i); + start.elapsed().as_millis() + })); + } + + let mut results: Vec = vec![]; + for handle in handles { + // TODO: a struct is returned from thread::spawn, can you use it? + } + + if results.len() != 10 { + panic!("Oh no! All the spawned threads did not finish!"); + } + + println!(); + for (i, result) in results.into_iter().enumerate() { + println!("thread {} took {}ms", i, result); + } +} diff --git a/exercises/20_threads/threads2.rs b/exercises/20_threads/threads2.rs new file mode 100644 index 0000000..62dad80 --- /dev/null +++ b/exercises/20_threads/threads2.rs @@ -0,0 +1,39 @@ +// threads2.rs +// +// 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 +// +// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +use std::sync::Arc; +use std::thread; +use std::time::Duration; + +struct JobStatus { + jobs_completed: u32, +} + +fn main() { + let status = Arc::new(JobStatus { jobs_completed: 0 }); + let mut handles = vec![]; + for _ in 0..10 { + let status_shared = Arc::clone(&status); + 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; + }); + handles.push(handle); + } + for handle in handles { + 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 {}", ???); + } +} diff --git a/exercises/20_threads/threads3.rs b/exercises/20_threads/threads3.rs new file mode 100644 index 0000000..91006bb --- /dev/null +++ b/exercises/20_threads/threads3.rs @@ -0,0 +1,67 @@ +// 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; +use std::time::Duration; + +struct Queue { + length: u32, + first_half: Vec, + second_half: Vec, +} + +impl Queue { + fn new() -> Self { + Queue { + length: 10, + first_half: vec![1, 2, 3, 4, 5], + second_half: vec![6, 7, 8, 9, 10], + } + } +} + +fn send_tx(q: Queue, tx: mpsc::Sender) -> () { + let qc = Arc::new(q); + let qc1 = Arc::clone(&qc); + let qc2 = Arc::clone(&qc); + + thread::spawn(move || { + for val in &qc1.first_half { + println!("sending {:?}", val); + tx.send(*val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + thread::spawn(move || { + for val in &qc2.second_half { + println!("sending {:?}", val); + tx.send(*val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); +} + +#[test] +fn main() { + let (tx, rx) = mpsc::channel(); + let queue = Queue::new(); + let queue_length = queue.length; + + send_tx(queue, tx); + + let mut total_received: u32 = 0; + for received in rx { + println!("Got: {}", received); + total_received += 1; + } + + println!("total numbers received: {}", total_received); + assert_eq!(total_received, queue_length) +} diff --git a/exercises/21_macros/README.md b/exercises/21_macros/README.md new file mode 100644 index 0000000..337816d --- /dev/null +++ b/exercises/21_macros/README.md @@ -0,0 +1,14 @@ +# Macros + +Rust's macro system is very powerful, but also kind of difficult to wrap your +head around. We're not going to teach you how to write your own fully-featured +macros. Instead, we'll show you how to use and create them. + +If you'd like to learn more about writing your own macros, the +[macrokata](https://github.com/tfpk/macrokata) project has a similar style +of exercises to Rustlings, but is all about learning to write Macros. + +## Further information + +- [Macros](https://doc.rust-lang.org/book/ch19-06-macros.html) +- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) diff --git a/exercises/21_macros/macros1.rs b/exercises/21_macros/macros1.rs new file mode 100644 index 0000000..678de6e --- /dev/null +++ b/exercises/21_macros/macros1.rs @@ -0,0 +1,16 @@ +// 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!"); + }; +} + +fn main() { + my_macro(); +} diff --git a/exercises/21_macros/macros2.rs b/exercises/21_macros/macros2.rs new file mode 100644 index 0000000..788fc16 --- /dev/null +++ b/exercises/21_macros/macros2.rs @@ -0,0 +1,16 @@ +// 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!"); + }; +} diff --git a/exercises/21_macros/macros3.rs b/exercises/21_macros/macros3.rs new file mode 100644 index 0000000..b795c14 --- /dev/null +++ b/exercises/21_macros/macros3.rs @@ -0,0 +1,20 @@ +// macros3.rs +// +// 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 + +mod macros { + macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + } +} + +fn main() { + my_macro!(); +} diff --git a/exercises/21_macros/macros4.rs b/exercises/21_macros/macros4.rs new file mode 100644 index 0000000..71b45a0 --- /dev/null +++ b/exercises/21_macros/macros4.rs @@ -0,0 +1,21 @@ +// macros4.rs +// +// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +#[rustfmt::skip] +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + } + ($val:expr) => { + println!("Look at this other macro: {}", $val); + } +} + +fn main() { + my_macro!(); + my_macro!(7777); +} diff --git a/exercises/22_clippy/README.md b/exercises/22_clippy/README.md new file mode 100644 index 0000000..55438af --- /dev/null +++ b/exercises/22_clippy/README.md @@ -0,0 +1,10 @@ +# Clippy + +The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code. + +If you used the installation script for Rustlings, Clippy should be already installed. +If not you can install it manually via `rustup component add clippy`. + +## Further information + +- [GitHub Repository](https://github.com/rust-lang/rust-clippy). diff --git a/exercises/22_clippy/clippy1.rs b/exercises/22_clippy/clippy1.rs new file mode 100644 index 0000000..95c0141 --- /dev/null +++ b/exercises/22_clippy/clippy1.rs @@ -0,0 +1,26 @@ +// clippy1.rs +// +// The Clippy tool is a collection of lints to analyze your code so you can +// catch common mistakes and improve your Rust code. +// +// For these exercises the code will fail to compile when there are clippy +// warnings 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 radius = 5.00f32; + + let area = pi * f32::powi(radius, 2); + + println!( + "The area of a circle with radius {:.2} is {:.5}!", + radius, area + ) +} diff --git a/exercises/22_clippy/clippy2.rs b/exercises/22_clippy/clippy2.rs new file mode 100644 index 0000000..9b87a0b --- /dev/null +++ b/exercises/22_clippy/clippy2.rs @@ -0,0 +1,15 @@ +// 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; + } + println!("{}", res); +} diff --git a/exercises/22_clippy/clippy3.rs b/exercises/22_clippy/clippy3.rs new file mode 100644 index 0000000..5a95f5b --- /dev/null +++ b/exercises/22_clippy/clippy3.rs @@ -0,0 +1,30 @@ +// clippy3.rs +// +// Here's a couple more easy Clippy fixes, so you can see its utility. +// No hints. + +// 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 + ]; + println!("My array! Here it is: {:?}", my_arr); + + let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); + 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; + println!("value a: {}; value b: {}", value_a, value_b); +} diff --git a/exercises/23_conversions/README.md b/exercises/23_conversions/README.md new file mode 100644 index 0000000..619a78c --- /dev/null +++ b/exercises/23_conversions/README.md @@ -0,0 +1,23 @@ +# Type conversions + +Rust offers a multitude of ways to convert a value of a given type into another type. + +The simplest form of type conversion is a type cast expression. It is denoted with the binary operator `as`. For instance, `println!("{}", 1 + 1.0);` would not compile, since `1` is an integer while `1.0` is a float. However, `println!("{}", 1 as f32 + 1.0)` should compile. The exercise [`using_as`](using_as.rs) tries to cover this. + +Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the [`convert`](https://doc.rust-lang.org/std/convert/index.html) module. +The traits are the following: + +- `From` and `Into` covered in [`from_into`](from_into.rs) +- `TryFrom` and `TryInto` covered in [`try_from_into`](try_from_into.rs) +- `AsRef` and `AsMut` covered in [`as_ref_mut`](as_ref_mut.rs) + +Furthermore, the `std::str` module offers a trait called [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) which helps with converting strings into target types via the `parse` method on strings. If properly implemented for a given type `Person`, then `let p: Person = "Mark,20".parse().unwrap()` should both compile and run without panicking. + +These should be the main ways ***within the standard library*** to convert data into your desired types. + +## Further information + +These are not directly covered in the book, but the standard library has a great documentation for it. + +- [conversions](https://doc.rust-lang.org/std/convert/index.html) +- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html) diff --git a/exercises/23_conversions/as_ref_mut.rs b/exercises/23_conversions/as_ref_mut.rs new file mode 100644 index 0000000..2ba9e3f --- /dev/null +++ b/exercises/23_conversions/as_ref_mut.rs @@ -0,0 +1,65 @@ +// as_ref_mut.rs +// +// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more +// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and +// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. +// +// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a +// hint. + +// I AM NOT DONE + +// Obtain the number of bytes (not characters) in the given argument. +// TODO: Add the AsRef trait appropriately as a trait bound. +fn byte_counter(arg: T) -> usize { + arg.as_ref().as_bytes().len() +} + +// Obtain the number of characters (not bytes) in the given argument. +// TODO: Add the AsRef trait appropriately as a trait bound. +fn char_counter(arg: T) -> usize { + arg.as_ref().chars().count() +} + +// Squares a number using as_mut(). +// TODO: Add the appropriate trait bound. +fn num_sq(arg: &mut T) { + // TODO: Implement the function body. + ??? +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn different_counts() { + let s = "Café au lait"; + assert_ne!(char_counter(s), byte_counter(s)); + } + + #[test] + fn same_counts() { + let s = "Cafe au lait"; + assert_eq!(char_counter(s), byte_counter(s)); + } + + #[test] + fn different_counts_using_string() { + let s = String::from("Café au lait"); + assert_ne!(char_counter(s.clone()), byte_counter(s)); + } + + #[test] + fn same_counts_using_string() { + let s = String::from("Cafe au lait"); + assert_eq!(char_counter(s.clone()), byte_counter(s)); + } + + #[test] + fn mut_box() { + let mut num: Box = Box::new(3); + num_sq(&mut num); + assert_eq!(*num, 9); + } +} diff --git a/exercises/23_conversions/from_into.rs b/exercises/23_conversions/from_into.rs new file mode 100644 index 0000000..60911f3 --- /dev/null +++ b/exercises/23_conversions/from_into.rs @@ -0,0 +1,140 @@ +// from_into.rs +// +// The From trait is used for value-to-value conversions. If From is implemented +// correctly for a type, the Into trait should work conversely. You can read +// more about it at https://doc.rust-lang.org/std/convert/trait.From.html +// +// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a +// hint. + +#[derive(Debug)] +struct Person { + name: String, + age: usize, +} + +// We implement the Default trait to use it as a fallback +// when the provided string is not convertible into a Person object +impl Default for Person { + fn default() -> Person { + Person { + name: String::from("John"), + age: 30, + } + } +} + +// Your task is to complete this implementation in order for the line `let p = +// Person::from("Mark,20")` to compile Please note that you'll need to parse the +// age component into a `usize` with something like `"4".parse::()`. The +// outcome of this needs to be handled appropriately. +// +// Steps: +// 1. If the length of the provided string is 0, then return the default of +// Person. +// 2. Split the given string on the commas present in it. +// 3. Extract the first element from the split operation and use it as the name. +// 4. If the name is empty, then return the default of Person. +// 5. Extract the other element from the split operation and parse it into a +// `usize` as the age. +// 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 { + } +} + +fn main() { + // Use the `from` function + let p1 = Person::from("Mark,20"); + // Since From is implemented for Person, we should be able to use Into + let p2: Person = "Gerald,70".into(); + println!("{:?}", p1); + println!("{:?}", p2); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn test_default() { + // Test that the default person is 30 year old John + let dp = Person::default(); + assert_eq!(dp.name, "John"); + assert_eq!(dp.age, 30); + } + #[test] + fn test_bad_convert() { + // Test that John is returned when bad string is provided + let p = Person::from(""); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + #[test] + fn test_good_convert() { + // Test that "Mark,20" works + let p = Person::from("Mark,20"); + assert_eq!(p.name, "Mark"); + assert_eq!(p.age, 20); + } + #[test] + fn test_bad_age() { + // Test that "Mark,twenty" will return the default person due to an + // error in parsing age + let p = Person::from("Mark,twenty"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_comma_and_age() { + let p: Person = Person::from("Mark"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_age() { + let p: Person = Person::from("Mark,"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name() { + let p: Person = Person::from(",1"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name_and_age() { + let p: Person = Person::from(","); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_missing_name_and_invalid_age() { + let p: Person = Person::from(",one"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_trailing_comma() { + let p: Person = Person::from("Mike,32,"); + assert_eq!(p.name, "Mike"); + assert_eq!(p.age, 32); + } + + #[test] + fn test_trailing_comma_and_some_string() { + let p: Person = Person::from("Mike,32,man"); + assert_eq!(p.name, "Mike"); + assert_eq!(p.age, 32); + } +} diff --git a/exercises/23_conversions/from_str.rs b/exercises/23_conversions/from_str.rs new file mode 100644 index 0000000..34472c3 --- /dev/null +++ b/exercises/23_conversions/from_str.rs @@ -0,0 +1,133 @@ +// from_str.rs +// +// This is similar to from_into.rs, but this time we'll implement `FromStr` and +// return errors instead of falling back to a default value. Additionally, upon +// implementing FromStr, you can use the `parse` method on strings to generate +// an object of the implementor type. You can read more about it at +// https://doc.rust-lang.org/std/str/trait.FromStr.html +// +// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a +// hint. + +use std::num::ParseIntError; +use std::str::FromStr; + +#[derive(Debug, PartialEq)] +struct Person { + name: String, + age: usize, +} + +// We will use this error type for the `FromStr` implementation. +#[derive(Debug, PartialEq)] +enum ParsePersonError { + // Empty input string + Empty, + // Incorrect number of fields + BadLen, + // Empty name field + NoName, + // Wrapped error from parse::() + 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 +// 3. Only 2 elements should be returned from the split, otherwise return an +// error +// 4. Extract the first element from the split operation and use it as the name +// 5. Extract the other element from the split operation and parse it into a +// `usize` as the age with something like `"4".parse::()` +// 6. If while extracting the name and the age something goes wrong, an error +// should be returned +// If everything goes well, then return a Result of a Person object +// +// As an aside: `Box` implements `From<&'_ str>`. This means that if +// you want to return a string error message, you can do so via just using +// return `Err("my error message".into())`. + +impl FromStr for Person { + type Err = ParsePersonError; + fn from_str(s: &str) -> Result { + } +} + +fn main() { + let p = "Mark,20".parse::().unwrap(); + println!("{:?}", p); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_input() { + assert_eq!("".parse::(), Err(ParsePersonError::Empty)); + } + #[test] + fn good_input() { + let p = "John,32".parse::(); + assert!(p.is_ok()); + let p = p.unwrap(); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 32); + } + #[test] + fn missing_age() { + assert!(matches!( + "John,".parse::(), + Err(ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn invalid_age() { + assert!(matches!( + "John,twenty".parse::(), + Err(ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn missing_comma_and_age() { + assert_eq!("John".parse::(), Err(ParsePersonError::BadLen)); + } + + #[test] + fn missing_name() { + assert_eq!(",1".parse::(), Err(ParsePersonError::NoName)); + } + + #[test] + fn missing_name_and_age() { + assert!(matches!( + ",".parse::(), + Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn missing_name_and_invalid_age() { + assert!(matches!( + ",one".parse::(), + Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) + )); + } + + #[test] + fn trailing_comma() { + assert_eq!("John,32,".parse::(), Err(ParsePersonError::BadLen)); + } + + #[test] + fn trailing_comma_and_some_string() { + assert_eq!( + "John,32,man".parse::(), + Err(ParsePersonError::BadLen) + ); + } +} diff --git a/exercises/23_conversions/try_from_into.rs b/exercises/23_conversions/try_from_into.rs new file mode 100644 index 0000000..32d6ef3 --- /dev/null +++ b/exercises/23_conversions/try_from_into.rs @@ -0,0 +1,193 @@ +// try_from_into.rs +// +// TryFrom is a simple and safe type conversion that may fail in a controlled +// way under some circumstances. Basically, this is the same as From. The main +// difference is that this should return a Result type instead of the target +// type itself. You can read more about it at +// https://doc.rust-lang.org/std/convert/trait.TryFrom.html +// +// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for +// a hint. + +use std::convert::{TryFrom, TryInto}; + +#[derive(Debug, PartialEq)] +struct Color { + red: u8, + green: u8, + blue: u8, +} + +// We will use this error type for these `TryFrom` conversions. +#[derive(Debug, PartialEq)] +enum IntoColorError { + // Incorrect length of slice + BadLen, + // Integer conversion error + 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, an array of three integers, and a slice of integers. +// +// Note that the implementation for tuple and array will be checked at compile +// time, but the slice implementation needs to check the slice length! Also note +// that correct RGB color values must be integers in the 0..=255 range. + +// Tuple implementation +impl TryFrom<(i16, i16, i16)> for Color { + type Error = IntoColorError; + fn try_from(tuple: (i16, i16, i16)) -> Result { + } +} + +// Array implementation +impl TryFrom<[i16; 3]> for Color { + type Error = IntoColorError; + fn try_from(arr: [i16; 3]) -> Result { + } +} + +// Slice implementation +impl TryFrom<&[i16]> for Color { + type Error = IntoColorError; + fn try_from(slice: &[i16]) -> Result { + } +} + +fn main() { + // Use the `try_from` function + let c1 = Color::try_from((183, 65, 14)); + println!("{:?}", c1); + + // Since TryFrom is implemented for Color, we should be able to use TryInto + let c2: Result = [183, 65, 14].try_into(); + println!("{:?}", c2); + + let v = vec![183, 65, 14]; + // With slice we should use `try_from` function + let c3 = Color::try_from(&v[..]); + println!("{:?}", c3); + // or take slice within round brackets and use TryInto + let c4: Result = (&v[..]).try_into(); + println!("{:?}", c4); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tuple_out_of_range_positive() { + assert_eq!( + Color::try_from((256, 1000, 10000)), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_tuple_out_of_range_negative() { + assert_eq!( + Color::try_from((-1, -10, -256)), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_tuple_sum() { + assert_eq!( + Color::try_from((-1, 255, 255)), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_tuple_correct() { + let c: Result = (183, 65, 14).try_into(); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + #[test] + fn test_array_out_of_range_positive() { + let c: Result = [1000, 10000, 256].try_into(); + assert_eq!(c, Err(IntoColorError::IntConversion)); + } + #[test] + fn test_array_out_of_range_negative() { + let c: Result = [-10, -256, -1].try_into(); + assert_eq!(c, Err(IntoColorError::IntConversion)); + } + #[test] + fn test_array_sum() { + let c: Result = [-1, 255, 255].try_into(); + assert_eq!(c, Err(IntoColorError::IntConversion)); + } + #[test] + fn test_array_correct() { + let c: Result = [183, 65, 14].try_into(); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + #[test] + fn test_slice_out_of_range_positive() { + let arr = [10000, 256, 1000]; + assert_eq!( + Color::try_from(&arr[..]), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_slice_out_of_range_negative() { + let arr = [-256, -1, -10]; + assert_eq!( + Color::try_from(&arr[..]), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_slice_sum() { + let arr = [-1, 255, 255]; + assert_eq!( + Color::try_from(&arr[..]), + Err(IntoColorError::IntConversion) + ); + } + #[test] + fn test_slice_correct() { + let v = vec![183, 65, 14]; + let c: Result = Color::try_from(&v[..]); + assert!(c.is_ok()); + assert_eq!( + c.unwrap(), + Color { + red: 183, + green: 65, + blue: 14 + } + ); + } + #[test] + fn test_slice_excess_length() { + let v = vec![0, 0, 0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); + } + #[test] + fn test_slice_insufficient_length() { + let v = vec![0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); + } +} diff --git a/exercises/23_conversions/using_as.rs b/exercises/23_conversions/using_as.rs new file mode 100644 index 0000000..414cef3 --- /dev/null +++ b/exercises/23_conversions/using_as.rs @@ -0,0 +1,33 @@ +// using_as.rs +// +// Type casting in Rust is done via the usage of the `as` operator. Please note +// that the `as` operator is not only used when type casting. It also helps with +// renaming imports. +// +// The goal is to make sure that the division does not fail to compile 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() +} + +fn main() { + let values = [3.5, 0.3, 13.0, 11.7]; + println!("{}", average(&values)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn returns_proper_type_and_value() { + assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125); + } +} diff --git a/exercises/clippy/README.md b/exercises/clippy/README.md deleted file mode 100644 index 55438af..0000000 --- a/exercises/clippy/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Clippy - -The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code. - -If you used the installation script for Rustlings, Clippy should be already installed. -If not you can install it manually via `rustup component add clippy`. - -## Further information - -- [GitHub Repository](https://github.com/rust-lang/rust-clippy). diff --git a/exercises/clippy/clippy1.rs b/exercises/clippy/clippy1.rs deleted file mode 100644 index 95c0141..0000000 --- a/exercises/clippy/clippy1.rs +++ /dev/null @@ -1,26 +0,0 @@ -// clippy1.rs -// -// The Clippy tool is a collection of lints to analyze your code so you can -// catch common mistakes and improve your Rust code. -// -// For these exercises the code will fail to compile when there are clippy -// warnings 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 radius = 5.00f32; - - let area = pi * f32::powi(radius, 2); - - println!( - "The area of a circle with radius {:.2} is {:.5}!", - radius, area - ) -} diff --git a/exercises/clippy/clippy2.rs b/exercises/clippy/clippy2.rs deleted file mode 100644 index 9b87a0b..0000000 --- a/exercises/clippy/clippy2.rs +++ /dev/null @@ -1,15 +0,0 @@ -// 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; - } - println!("{}", res); -} diff --git a/exercises/clippy/clippy3.rs b/exercises/clippy/clippy3.rs deleted file mode 100644 index 5a95f5b..0000000 --- a/exercises/clippy/clippy3.rs +++ /dev/null @@ -1,30 +0,0 @@ -// clippy3.rs -// -// Here's a couple more easy Clippy fixes, so you can see its utility. -// No hints. - -// 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 - ]; - println!("My array! Here it is: {:?}", my_arr); - - let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5); - 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; - println!("value a: {}; value b: {}", value_a, value_b); -} diff --git a/exercises/conversions/README.md b/exercises/conversions/README.md deleted file mode 100644 index 619a78c..0000000 --- a/exercises/conversions/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Type conversions - -Rust offers a multitude of ways to convert a value of a given type into another type. - -The simplest form of type conversion is a type cast expression. It is denoted with the binary operator `as`. For instance, `println!("{}", 1 + 1.0);` would not compile, since `1` is an integer while `1.0` is a float. However, `println!("{}", 1 as f32 + 1.0)` should compile. The exercise [`using_as`](using_as.rs) tries to cover this. - -Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the [`convert`](https://doc.rust-lang.org/std/convert/index.html) module. -The traits are the following: - -- `From` and `Into` covered in [`from_into`](from_into.rs) -- `TryFrom` and `TryInto` covered in [`try_from_into`](try_from_into.rs) -- `AsRef` and `AsMut` covered in [`as_ref_mut`](as_ref_mut.rs) - -Furthermore, the `std::str` module offers a trait called [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) which helps with converting strings into target types via the `parse` method on strings. If properly implemented for a given type `Person`, then `let p: Person = "Mark,20".parse().unwrap()` should both compile and run without panicking. - -These should be the main ways ***within the standard library*** to convert data into your desired types. - -## Further information - -These are not directly covered in the book, but the standard library has a great documentation for it. - -- [conversions](https://doc.rust-lang.org/std/convert/index.html) -- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html) diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs deleted file mode 100644 index 2ba9e3f..0000000 --- a/exercises/conversions/as_ref_mut.rs +++ /dev/null @@ -1,65 +0,0 @@ -// as_ref_mut.rs -// -// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more -// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and -// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. -// -// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -// Obtain the number of bytes (not characters) in the given argument. -// TODO: Add the AsRef trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { - arg.as_ref().as_bytes().len() -} - -// Obtain the number of characters (not bytes) in the given argument. -// TODO: Add the AsRef trait appropriately as a trait bound. -fn char_counter(arg: T) -> usize { - arg.as_ref().chars().count() -} - -// Squares a number using as_mut(). -// TODO: Add the appropriate trait bound. -fn num_sq(arg: &mut T) { - // TODO: Implement the function body. - ??? -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn different_counts() { - let s = "Café au lait"; - assert_ne!(char_counter(s), byte_counter(s)); - } - - #[test] - fn same_counts() { - let s = "Cafe au lait"; - assert_eq!(char_counter(s), byte_counter(s)); - } - - #[test] - fn different_counts_using_string() { - let s = String::from("Café au lait"); - assert_ne!(char_counter(s.clone()), byte_counter(s)); - } - - #[test] - fn same_counts_using_string() { - let s = String::from("Cafe au lait"); - assert_eq!(char_counter(s.clone()), byte_counter(s)); - } - - #[test] - fn mut_box() { - let mut num: Box = Box::new(3); - num_sq(&mut num); - assert_eq!(*num, 9); - } -} diff --git a/exercises/conversions/from_into.rs b/exercises/conversions/from_into.rs deleted file mode 100644 index 60911f3..0000000 --- a/exercises/conversions/from_into.rs +++ /dev/null @@ -1,140 +0,0 @@ -// from_into.rs -// -// The From trait is used for value-to-value conversions. If From is implemented -// correctly for a type, the Into trait should work conversely. You can read -// more about it at https://doc.rust-lang.org/std/convert/trait.From.html -// -// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a -// hint. - -#[derive(Debug)] -struct Person { - name: String, - age: usize, -} - -// We implement the Default trait to use it as a fallback -// when the provided string is not convertible into a Person object -impl Default for Person { - fn default() -> Person { - Person { - name: String::from("John"), - age: 30, - } - } -} - -// Your task is to complete this implementation in order for the line `let p = -// Person::from("Mark,20")` to compile Please note that you'll need to parse the -// age component into a `usize` with something like `"4".parse::()`. The -// outcome of this needs to be handled appropriately. -// -// Steps: -// 1. If the length of the provided string is 0, then return the default of -// Person. -// 2. Split the given string on the commas present in it. -// 3. Extract the first element from the split operation and use it as the name. -// 4. If the name is empty, then return the default of Person. -// 5. Extract the other element from the split operation and parse it into a -// `usize` as the age. -// 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 { - } -} - -fn main() { - // Use the `from` function - let p1 = Person::from("Mark,20"); - // Since From is implemented for Person, we should be able to use Into - let p2: Person = "Gerald,70".into(); - println!("{:?}", p1); - println!("{:?}", p2); -} - -#[cfg(test)] -mod tests { - use super::*; - #[test] - fn test_default() { - // Test that the default person is 30 year old John - let dp = Person::default(); - assert_eq!(dp.name, "John"); - assert_eq!(dp.age, 30); - } - #[test] - fn test_bad_convert() { - // Test that John is returned when bad string is provided - let p = Person::from(""); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - #[test] - fn test_good_convert() { - // Test that "Mark,20" works - let p = Person::from("Mark,20"); - assert_eq!(p.name, "Mark"); - assert_eq!(p.age, 20); - } - #[test] - fn test_bad_age() { - // Test that "Mark,twenty" will return the default person due to an - // error in parsing age - let p = Person::from("Mark,twenty"); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_missing_comma_and_age() { - let p: Person = Person::from("Mark"); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_missing_age() { - let p: Person = Person::from("Mark,"); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_missing_name() { - let p: Person = Person::from(",1"); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_missing_name_and_age() { - let p: Person = Person::from(","); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_missing_name_and_invalid_age() { - let p: Person = Person::from(",one"); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_trailing_comma() { - let p: Person = Person::from("Mike,32,"); - assert_eq!(p.name, "Mike"); - assert_eq!(p.age, 32); - } - - #[test] - fn test_trailing_comma_and_some_string() { - let p: Person = Person::from("Mike,32,man"); - assert_eq!(p.name, "Mike"); - assert_eq!(p.age, 32); - } -} diff --git a/exercises/conversions/from_str.rs b/exercises/conversions/from_str.rs deleted file mode 100644 index 34472c3..0000000 --- a/exercises/conversions/from_str.rs +++ /dev/null @@ -1,133 +0,0 @@ -// from_str.rs -// -// This is similar to from_into.rs, but this time we'll implement `FromStr` and -// return errors instead of falling back to a default value. Additionally, upon -// implementing FromStr, you can use the `parse` method on strings to generate -// an object of the implementor type. You can read more about it at -// https://doc.rust-lang.org/std/str/trait.FromStr.html -// -// Execute `rustlings hint from_str` or use the `hint` watch subcommand for a -// hint. - -use std::num::ParseIntError; -use std::str::FromStr; - -#[derive(Debug, PartialEq)] -struct Person { - name: String, - age: usize, -} - -// We will use this error type for the `FromStr` implementation. -#[derive(Debug, PartialEq)] -enum ParsePersonError { - // Empty input string - Empty, - // Incorrect number of fields - BadLen, - // Empty name field - NoName, - // Wrapped error from parse::() - 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 -// 3. Only 2 elements should be returned from the split, otherwise return an -// error -// 4. Extract the first element from the split operation and use it as the name -// 5. Extract the other element from the split operation and parse it into a -// `usize` as the age with something like `"4".parse::()` -// 6. If while extracting the name and the age something goes wrong, an error -// should be returned -// If everything goes well, then return a Result of a Person object -// -// As an aside: `Box` implements `From<&'_ str>`. This means that if -// you want to return a string error message, you can do so via just using -// return `Err("my error message".into())`. - -impl FromStr for Person { - type Err = ParsePersonError; - fn from_str(s: &str) -> Result { - } -} - -fn main() { - let p = "Mark,20".parse::().unwrap(); - println!("{:?}", p); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn empty_input() { - assert_eq!("".parse::(), Err(ParsePersonError::Empty)); - } - #[test] - fn good_input() { - let p = "John,32".parse::(); - assert!(p.is_ok()); - let p = p.unwrap(); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 32); - } - #[test] - fn missing_age() { - assert!(matches!( - "John,".parse::(), - Err(ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn invalid_age() { - assert!(matches!( - "John,twenty".parse::(), - Err(ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn missing_comma_and_age() { - assert_eq!("John".parse::(), Err(ParsePersonError::BadLen)); - } - - #[test] - fn missing_name() { - assert_eq!(",1".parse::(), Err(ParsePersonError::NoName)); - } - - #[test] - fn missing_name_and_age() { - assert!(matches!( - ",".parse::(), - Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn missing_name_and_invalid_age() { - assert!(matches!( - ",one".parse::(), - Err(ParsePersonError::NoName | ParsePersonError::ParseInt(_)) - )); - } - - #[test] - fn trailing_comma() { - assert_eq!("John,32,".parse::(), Err(ParsePersonError::BadLen)); - } - - #[test] - fn trailing_comma_and_some_string() { - assert_eq!( - "John,32,man".parse::(), - Err(ParsePersonError::BadLen) - ); - } -} diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs deleted file mode 100644 index 32d6ef3..0000000 --- a/exercises/conversions/try_from_into.rs +++ /dev/null @@ -1,193 +0,0 @@ -// try_from_into.rs -// -// TryFrom is a simple and safe type conversion that may fail in a controlled -// way under some circumstances. Basically, this is the same as From. The main -// difference is that this should return a Result type instead of the target -// type itself. You can read more about it at -// https://doc.rust-lang.org/std/convert/trait.TryFrom.html -// -// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for -// a hint. - -use std::convert::{TryFrom, TryInto}; - -#[derive(Debug, PartialEq)] -struct Color { - red: u8, - green: u8, - blue: u8, -} - -// We will use this error type for these `TryFrom` conversions. -#[derive(Debug, PartialEq)] -enum IntoColorError { - // Incorrect length of slice - BadLen, - // Integer conversion error - 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, an array of three integers, and a slice of integers. -// -// Note that the implementation for tuple and array will be checked at compile -// time, but the slice implementation needs to check the slice length! Also note -// that correct RGB color values must be integers in the 0..=255 range. - -// Tuple implementation -impl TryFrom<(i16, i16, i16)> for Color { - type Error = IntoColorError; - fn try_from(tuple: (i16, i16, i16)) -> Result { - } -} - -// Array implementation -impl TryFrom<[i16; 3]> for Color { - type Error = IntoColorError; - fn try_from(arr: [i16; 3]) -> Result { - } -} - -// Slice implementation -impl TryFrom<&[i16]> for Color { - type Error = IntoColorError; - fn try_from(slice: &[i16]) -> Result { - } -} - -fn main() { - // Use the `try_from` function - let c1 = Color::try_from((183, 65, 14)); - println!("{:?}", c1); - - // Since TryFrom is implemented for Color, we should be able to use TryInto - let c2: Result = [183, 65, 14].try_into(); - println!("{:?}", c2); - - let v = vec![183, 65, 14]; - // With slice we should use `try_from` function - let c3 = Color::try_from(&v[..]); - println!("{:?}", c3); - // or take slice within round brackets and use TryInto - let c4: Result = (&v[..]).try_into(); - println!("{:?}", c4); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_tuple_out_of_range_positive() { - assert_eq!( - Color::try_from((256, 1000, 10000)), - Err(IntoColorError::IntConversion) - ); - } - #[test] - fn test_tuple_out_of_range_negative() { - assert_eq!( - Color::try_from((-1, -10, -256)), - Err(IntoColorError::IntConversion) - ); - } - #[test] - fn test_tuple_sum() { - assert_eq!( - Color::try_from((-1, 255, 255)), - Err(IntoColorError::IntConversion) - ); - } - #[test] - fn test_tuple_correct() { - let c: Result = (183, 65, 14).try_into(); - assert!(c.is_ok()); - assert_eq!( - c.unwrap(), - Color { - red: 183, - green: 65, - blue: 14 - } - ); - } - #[test] - fn test_array_out_of_range_positive() { - let c: Result = [1000, 10000, 256].try_into(); - assert_eq!(c, Err(IntoColorError::IntConversion)); - } - #[test] - fn test_array_out_of_range_negative() { - let c: Result = [-10, -256, -1].try_into(); - assert_eq!(c, Err(IntoColorError::IntConversion)); - } - #[test] - fn test_array_sum() { - let c: Result = [-1, 255, 255].try_into(); - assert_eq!(c, Err(IntoColorError::IntConversion)); - } - #[test] - fn test_array_correct() { - let c: Result = [183, 65, 14].try_into(); - assert!(c.is_ok()); - assert_eq!( - c.unwrap(), - Color { - red: 183, - green: 65, - blue: 14 - } - ); - } - #[test] - fn test_slice_out_of_range_positive() { - let arr = [10000, 256, 1000]; - assert_eq!( - Color::try_from(&arr[..]), - Err(IntoColorError::IntConversion) - ); - } - #[test] - fn test_slice_out_of_range_negative() { - let arr = [-256, -1, -10]; - assert_eq!( - Color::try_from(&arr[..]), - Err(IntoColorError::IntConversion) - ); - } - #[test] - fn test_slice_sum() { - let arr = [-1, 255, 255]; - assert_eq!( - Color::try_from(&arr[..]), - Err(IntoColorError::IntConversion) - ); - } - #[test] - fn test_slice_correct() { - let v = vec![183, 65, 14]; - let c: Result = Color::try_from(&v[..]); - assert!(c.is_ok()); - assert_eq!( - c.unwrap(), - Color { - red: 183, - green: 65, - blue: 14 - } - ); - } - #[test] - fn test_slice_excess_length() { - let v = vec![0, 0, 0, 0]; - assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); - } - #[test] - fn test_slice_insufficient_length() { - let v = vec![0, 0]; - assert_eq!(Color::try_from(&v[..]), Err(IntoColorError::BadLen)); - } -} diff --git a/exercises/conversions/using_as.rs b/exercises/conversions/using_as.rs deleted file mode 100644 index 414cef3..0000000 --- a/exercises/conversions/using_as.rs +++ /dev/null @@ -1,33 +0,0 @@ -// using_as.rs -// -// Type casting in Rust is done via the usage of the `as` operator. Please note -// that the `as` operator is not only used when type casting. It also helps with -// renaming imports. -// -// The goal is to make sure that the division does not fail to compile 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() -} - -fn main() { - let values = [3.5, 0.3, 13.0, 11.7]; - println!("{}", average(&values)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn returns_proper_type_and_value() { - assert_eq!(average(&[3.5, 0.3, 13.0, 11.7]), 7.125); - } -} diff --git a/exercises/enums/README.md b/exercises/enums/README.md deleted file mode 100644 index 30d4d91..0000000 --- a/exercises/enums/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# 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. -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/ch18-03-pattern-syntax.html) diff --git a/exercises/enums/enums1.rs b/exercises/enums/enums1.rs deleted file mode 100644 index 25525b2..0000000 --- a/exercises/enums/enums1.rs +++ /dev/null @@ -1,17 +0,0 @@ -// enums1.rs -// -// No hints this time! ;) - -// I AM NOT DONE - -#[derive(Debug)] -enum Message { - // TODO: define a few types of messages as used below -} - -fn main() { - println!("{:?}", Message::Quit); - println!("{:?}", Message::Echo); - println!("{:?}", Message::Move); - println!("{:?}", Message::ChangeColor); -} diff --git a/exercises/enums/enums2.rs b/exercises/enums/enums2.rs deleted file mode 100644 index df93fe0..0000000 --- a/exercises/enums/enums2.rs +++ /dev/null @@ -1,30 +0,0 @@ -// 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 -} - -impl Message { - fn call(&self) { - println!("{:?}", self); - } -} - -fn main() { - let messages = [ - Message::Move { x: 10, y: 30 }, - Message::Echo(String::from("hello world")), - Message::ChangeColor(200, 255, 255), - Message::Quit, - ]; - - for message in &messages { - message.call(); - } -} diff --git a/exercises/enums/enums3.rs b/exercises/enums/enums3.rs deleted file mode 100644 index 92d18c4..0000000 --- a/exercises/enums/enums3.rs +++ /dev/null @@ -1,73 +0,0 @@ -// enums3.rs -// -// 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 -} - -struct Point { - x: u8, - y: u8, -} - -struct State { - color: (u8, u8, u8), - position: Point, - quit: bool, - message: String, -} - -impl State { - fn change_color(&mut self, color: (u8, u8, u8)) { - self.color = color; - } - - fn quit(&mut self) { - self.quit = true; - } - - fn echo(&mut self, s: String) { - self.message = s - } - - fn move_position(&mut self, p: Point) { - self.position = p; - } - - fn process(&mut self, message: Message) { - // TODO: create a match expression to process the different message variants - // Remember: When passing a tuple as a function argument, you'll need extra parentheses: - // fn function((t, u, p, l, e)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_match_message_call() { - let mut state = State { - quit: false, - position: Point { x: 0, y: 0 }, - color: (0, 0, 0), - message: "hello world".to_string(), - }; - state.process(Message::ChangeColor(255, 0, 255)); - state.process(Message::Echo(String::from("Hello world!"))); - state.process(Message::Move(Point { x: 10, y: 15 })); - state.process(Message::Quit); - - assert_eq!(state.color, (255, 0, 255)); - assert_eq!(state.position.x, 10); - assert_eq!(state.position.y, 15); - assert_eq!(state.quit, true); - assert_eq!(state.message, "Hello world!"); - } -} diff --git a/exercises/error_handling/README.md b/exercises/error_handling/README.md deleted file mode 100644 index 3b21f2b..0000000 --- a/exercises/error_handling/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# 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. - -## Further information - -- [Error Handling](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html) -- [Generics](https://doc.rust-lang.org/book/ch10-01-syntax.html) -- [Result](https://doc.rust-lang.org/rust-by-example/error/result.html) -- [Boxing errors](https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/boxing_errors.html) diff --git a/exercises/error_handling/errors1.rs b/exercises/error_handling/errors1.rs deleted file mode 100644 index 0ba59a5..0000000 --- a/exercises/error_handling/errors1.rs +++ /dev/null @@ -1,43 +0,0 @@ -// errors1.rs -// -// This function refuses to generate text to be printed on a nametag if you pass -// it an empty string. It'd be nicer if it explained what the problem was, -// instead of just sometimes returning `None`. Thankfully, Rust has a similar -// 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 { - if name.is_empty() { - // Empty names aren't allowed. - None - } else { - Some(format!("Hi! My name is {}", name)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generates_nametag_text_for_a_nonempty_name() { - assert_eq!( - generate_nametag_text("Beyoncé".into()), - Ok("Hi! My name is Beyoncé".into()) - ); - } - - #[test] - fn explains_why_generating_nametag_text_fails() { - assert_eq!( - generate_nametag_text("".into()), - // Don't change this line - Err("`name` was empty; it must be nonempty.".into()) - ); - } -} diff --git a/exercises/error_handling/errors2.rs b/exercises/error_handling/errors2.rs deleted file mode 100644 index 631fe67..0000000 --- a/exercises/error_handling/errors2.rs +++ /dev/null @@ -1,50 +0,0 @@ -// errors2.rs -// -// Say we're writing a game where you can buy items with tokens. All items cost -// 5 tokens, and whenever you purchase items there is a processing fee of 1 -// token. A player of the game will type in how many items they want to buy, and -// the `total_cost` function will calculate the total cost of the items. Since -// the player typed in the quantity, though, we get it as a string-- and they -// might have typed anything, not just numbers! -// -// Right now, this function isn't handling the error case at all (and isn't -// handling the success case properly either). What we want to do is: if we call -// the `total_cost` function on a string that is not a number, that function -// will return a `ParseIntError`, and in that case, we want to immediately -// return that error from our function and not try to multiply and add. -// -// There are at least two ways to implement this that are both correct-- but 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::(); - - Ok(qty * cost_per_item + processing_fee) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn item_quantity_is_a_valid_number() { - assert_eq!(total_cost("34"), Ok(171)); - } - - #[test] - fn item_quantity_is_an_invalid_number() { - assert_eq!( - total_cost("beep boop").unwrap_err().to_string(), - "invalid digit found in string" - ); - } -} diff --git a/exercises/error_handling/errors3.rs b/exercises/error_handling/errors3.rs deleted file mode 100644 index d42d3b1..0000000 --- a/exercises/error_handling/errors3.rs +++ /dev/null @@ -1,34 +0,0 @@ -// errors3.rs -// -// This is a program that is trying to use a completed version of the -// `total_cost` function from the previous exercise. It's not working though! -// 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() { - let mut tokens = 100; - let pretend_user_input = "8"; - - let cost = total_cost(pretend_user_input)?; - - if cost > tokens { - println!("You can't afford that many!"); - } else { - tokens -= cost; - println!("You now have {} tokens.", tokens); - } -} - -pub fn total_cost(item_quantity: &str) -> Result { - let processing_fee = 1; - let cost_per_item = 5; - let qty = item_quantity.parse::()?; - - Ok(qty * cost_per_item + processing_fee) -} diff --git a/exercises/error_handling/errors4.rs b/exercises/error_handling/errors4.rs deleted file mode 100644 index d6d6fcb..0000000 --- a/exercises/error_handling/errors4.rs +++ /dev/null @@ -1,32 +0,0 @@ -// 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); - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - // Hmm... Why is this always returning an Ok value? - Ok(PositiveNonzeroInteger(value as u64)) - } -} - -#[test] -fn test_creation() { - assert!(PositiveNonzeroInteger::new(10).is_ok()); - assert_eq!( - Err(CreationError::Negative), - PositiveNonzeroInteger::new(-10) - ); - assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0)); -} diff --git a/exercises/error_handling/errors5.rs b/exercises/error_handling/errors5.rs deleted file mode 100644 index 92461a7..0000000 --- a/exercises/error_handling/errors5.rs +++ /dev/null @@ -1,71 +0,0 @@ -// errors5.rs -// -// This program uses an altered version of the code from errors4. -// -// This exercise uses some concepts that we won't get to until later in the -// course, like `Box` and the `From` trait. It's not important to understand -// them in detail right now, but you can read ahead if you like. For now, think -// of the `Box` type as an "I want anything that does ???" type, which, -// given Rust's usual standards for runtime safety, should strike you as -// somewhat lenient! -// -// 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 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. -// -// What can we use to describe both errors? In other words, is there a trait -// which both errors implement? -// -// 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> { - let pretend_user_input = "42"; - let x: i64 = pretend_user_input.parse()?; - println!("output={:?}", PositiveNonzeroInteger::new(x)?); - Ok(()) -} - -// Don't change anything below this line. - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - x if x == 0 => Err(CreationError::Zero), - x => Ok(PositiveNonzeroInteger(x as u64)), - } - } -} - -// This is required so that `CreationError` can implement `error::Error`. -impl fmt::Display for CreationError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let description = match *self { - CreationError::Negative => "number is negative", - CreationError::Zero => "number is zero", - }; - f.write_str(description) - } -} - -impl error::Error for CreationError {} diff --git a/exercises/error_handling/errors6.rs b/exercises/error_handling/errors6.rs deleted file mode 100644 index aaf0948..0000000 --- a/exercises/error_handling/errors6.rs +++ /dev/null @@ -1,94 +0,0 @@ -// errors6.rs -// -// Using catch-all error types like `Box` isn't recommended -// for library code, where callers might want to make decisions based on the -// error content, instead of printing it out or propagating it further. Here, we -// define a custom error type to make it possible for callers to decide what to -// do next when our function returns an error. -// -// 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()`. -#[derive(PartialEq, Debug)] -enum ParsePosNonzeroError { - Creation(CreationError), - ParseInt(ParseIntError), -} - -impl ParsePosNonzeroError { - fn from_creation(err: CreationError) -> ParsePosNonzeroError { - ParsePosNonzeroError::Creation(err) - } - // TODO: add another error conversion function here. - // fn from_parseint... -} - -fn parse_pos_nonzero(s: &str) -> Result { - // TODO: change this to return an appropriate error instead of panicking - // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); - PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) -} - -// Don't change anything below this line. - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - x if x == 0 => Err(CreationError::Zero), - x => Ok(PositiveNonzeroInteger(x as u64)), - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_parse_error() { - // We can't construct a ParseIntError, so we have to pattern match. - assert!(matches!( - parse_pos_nonzero("not a number"), - Err(ParsePosNonzeroError::ParseInt(_)) - )); - } - - #[test] - fn test_negative() { - assert_eq!( - parse_pos_nonzero("-555"), - Err(ParsePosNonzeroError::Creation(CreationError::Negative)) - ); - } - - #[test] - fn test_zero() { - assert_eq!( - parse_pos_nonzero("0"), - Err(ParsePosNonzeroError::Creation(CreationError::Zero)) - ); - } - - #[test] - fn test_positive() { - let x = PositiveNonzeroInteger::new(42); - assert!(x.is_ok()); - assert_eq!(parse_pos_nonzero("42"), Ok(x.unwrap())); - } -} diff --git a/exercises/functions/README.md b/exercises/functions/README.md deleted file mode 100644 index 6662d0d..0000000 --- a/exercises/functions/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Functions - -Here, you'll learn how to write functions and how the Rust compiler can help you debug errors even -in more complex code. - -## Further information - -- [How Functions Work](https://doc.rust-lang.org/book/ch03-03-how-functions-work.html) diff --git a/exercises/functions/functions1.rs b/exercises/functions/functions1.rs deleted file mode 100644 index 40ed9a0..0000000 --- a/exercises/functions/functions1.rs +++ /dev/null @@ -1,10 +0,0 @@ -// functions1.rs -// -// Execute `rustlings hint functions1` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - call_me(); -} diff --git a/exercises/functions/functions2.rs b/exercises/functions/functions2.rs deleted file mode 100644 index 5154f34..0000000 --- a/exercises/functions/functions2.rs +++ /dev/null @@ -1,16 +0,0 @@ -// 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:) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} diff --git a/exercises/functions/functions3.rs b/exercises/functions/functions3.rs deleted file mode 100644 index 74f44d6..0000000 --- a/exercises/functions/functions3.rs +++ /dev/null @@ -1,16 +0,0 @@ -// functions3.rs -// -// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - call_me(); -} - -fn call_me(num: u32) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} diff --git a/exercises/functions/functions4.rs b/exercises/functions/functions4.rs deleted file mode 100644 index 77c4b2a..0000000 --- a/exercises/functions/functions4.rs +++ /dev/null @@ -1,28 +0,0 @@ -// functions4.rs -// -// This store is having a sale where if the price is an even number, you get 10 -// Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. (Don't worry -// about the function bodies themselves, we're only interested in the signatures -// for now. If anything, this is a good way to peek ahead to future exercises!) -// -// Execute `rustlings hint functions4` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - let original_price = 51; - println!("Your sale price is {}", sale_price(original_price)); -} - -fn sale_price(price: i32) -> { - if is_even(price) { - price - 10 - } else { - price - 3 - } -} - -fn is_even(num: i32) -> bool { - num % 2 == 0 -} diff --git a/exercises/functions/functions5.rs b/exercises/functions/functions5.rs deleted file mode 100644 index f1b63f4..0000000 --- a/exercises/functions/functions5.rs +++ /dev/null @@ -1,15 +0,0 @@ -// 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; -} diff --git a/exercises/generics/README.md b/exercises/generics/README.md deleted file mode 100644 index de46d50..0000000 --- a/exercises/generics/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Generics - -Generics is the topic of generalizing types and functionalities to broader cases. -This is extremely useful for reducing code duplication in many ways, but can call for rather involving syntax. -Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid. -The simplest and most common use of generics is for type parameters. - -## Further information - -- [Generic Data Types](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html) -- [Bounds](https://doc.rust-lang.org/rust-by-example/generics/bounds.html) diff --git a/exercises/generics/generics1.rs b/exercises/generics/generics1.rs deleted file mode 100644 index 35c1d2f..0000000 --- a/exercises/generics/generics1.rs +++ /dev/null @@ -1,14 +0,0 @@ -// generics1.rs -// -// This shopping list program isn't compiling! Use your knowledge of generics to -// fix it. -// -// 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(); - shopping_list.push("milk"); -} diff --git a/exercises/generics/generics2.rs b/exercises/generics/generics2.rs deleted file mode 100644 index 074cd93..0000000 --- a/exercises/generics/generics2.rs +++ /dev/null @@ -1,34 +0,0 @@ -// generics2.rs -// -// This powerful wrapper provides the ability to store a positive integer value. -// Rewrite it using generics so that it supports wrapping ANY type. -// -// Execute `rustlings hint generics2` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -struct Wrapper { - value: u32, -} - -impl Wrapper { - pub fn new(value: u32) -> Self { - Wrapper { value } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn store_u32_in_wrapper() { - assert_eq!(Wrapper::new(42).value, 42); - } - - #[test] - fn store_str_in_wrapper() { - assert_eq!(Wrapper::new("Foo").value, "Foo"); - } -} diff --git a/exercises/hashmaps/README.md b/exercises/hashmaps/README.md deleted file mode 100644 index 80ec144..0000000 --- a/exercises/hashmaps/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Hashmaps - -A *hash map* allows you to associate a value with a particular key. -You may also know this by the names [*unordered map* in C++](https://en.cppreference.com/w/cpp/container/unordered_map), -[*dictionary* in Python](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) or an *associative array* in other languages. - -This is the other data structure that we've been talking about before, when -talking about Vecs. - -## Further information - -- [Storing Keys with Associated Values in Hash Maps](https://doc.rust-lang.org/book/ch08-03-hash-maps.html) diff --git a/exercises/hashmaps/hashmaps1.rs b/exercises/hashmaps/hashmaps1.rs deleted file mode 100644 index 80829ea..0000000 --- a/exercises/hashmaps/hashmaps1.rs +++ /dev/null @@ -1,44 +0,0 @@ -// hashmaps1.rs -// -// A basket of fruits in the form of a hash map needs to be defined. The key -// represents the name of the fruit and the value represents how many of that -// particular fruit is in the basket. You have to put at least three different -// types of fruits (e.g apple, banana, mango) in the basket and the total count -// of all the fruits should be at least five. -// -// Make me compile and pass the tests! -// -// 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. - - // Two bananas are already given for you :) - basket.insert(String::from("banana"), 2); - - // TODO: Put more fruits in your basket here. - - basket -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn at_least_three_types_of_fruits() { - let basket = fruit_basket(); - assert!(basket.len() >= 3); - } - - #[test] - fn at_least_five_fruits() { - let basket = fruit_basket(); - assert!(basket.values().sum::() >= 5); - } -} diff --git a/exercises/hashmaps/hashmaps2.rs b/exercises/hashmaps/hashmaps2.rs deleted file mode 100644 index a592569..0000000 --- a/exercises/hashmaps/hashmaps2.rs +++ /dev/null @@ -1,93 +0,0 @@ -// hashmaps2.rs -// -// We're collecting different fruits to bake a delicious fruit cake. For this, -// we have a basket, which we'll represent in the form of a hash map. The key -// represents the name of each fruit we collect and the value represents how -// many of that particular fruit we have collected. Three types of fruits - -// Apple (4), Mango (2) and Lychee (5) are already in the basket hash map. You -// must add fruit to the basket so that there is at least one of each kind and -// more than 11 in total - we have a lot of mouths to feed. You are not allowed -// to insert any more of these fruits! -// -// Make me pass the tests! -// -// 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)] -enum Fruit { - Apple, - Banana, - Mango, - Lychee, - Pineapple, -} - -fn fruit_basket(basket: &mut HashMap) { - let fruit_kinds = vec![ - Fruit::Apple, - Fruit::Banana, - Fruit::Mango, - Fruit::Lychee, - Fruit::Pineapple, - ]; - - for fruit in fruit_kinds { - // TODO: Insert new fruits if they are not already present in the - // basket. Note that you are not allowed to put any type of fruit that's - // already present! - } -} - -#[cfg(test)] -mod tests { - use super::*; - - // Don't modify this function! - fn get_fruit_basket() -> HashMap { - let mut basket = HashMap::::new(); - basket.insert(Fruit::Apple, 4); - basket.insert(Fruit::Mango, 2); - basket.insert(Fruit::Lychee, 5); - - basket - } - - #[test] - fn test_given_fruits_are_not_modified() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - assert_eq!(*basket.get(&Fruit::Apple).unwrap(), 4); - assert_eq!(*basket.get(&Fruit::Mango).unwrap(), 2); - assert_eq!(*basket.get(&Fruit::Lychee).unwrap(), 5); - } - - #[test] - fn at_least_five_types_of_fruits() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - let count_fruit_kinds = basket.len(); - assert!(count_fruit_kinds >= 5); - } - - #[test] - fn greater_than_eleven_fruits() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - let count = basket.values().sum::(); - assert!(count > 11); - } - - #[test] - fn all_fruit_types_in_basket() { - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - for amount in basket.values() { - assert_ne!(amount, &0); - } - } -} diff --git a/exercises/hashmaps/hashmaps3.rs b/exercises/hashmaps/hashmaps3.rs deleted file mode 100644 index 08e977c..0000000 --- a/exercises/hashmaps/hashmaps3.rs +++ /dev/null @@ -1,86 +0,0 @@ -// hashmaps3.rs -// -// A list of scores (one per line) of a soccer match is given. Each line is of -// the form : ",,," -// Example: England,France,4,2 (England scored 4 goals, France 2). -// -// You have to build a scores table containing the name of the team, goals the -// team scored, and goals the team conceded. One approach to build the scores -// table is to use a Hashmap. The solution is partially written to use a -// Hashmap, complete it to pass the test. -// -// Make me pass the tests! -// -// Execute `rustlings hint hashmaps3` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -use std::collections::HashMap; - -// A structure to store the goal details of a team. -struct Team { - goals_scored: u8, - goals_conceded: u8, -} - -fn build_scores_table(results: String) -> HashMap { - // The name of the team is the key and its associated struct is the value. - let mut scores: HashMap = HashMap::new(); - - for r in results.lines() { - let v: Vec<&str> = r.split(',').collect(); - let team_1_name = v[0].to_string(); - let team_1_score: u8 = v[2].parse().unwrap(); - let team_2_name = v[1].to_string(); - let team_2_score: u8 = v[3].parse().unwrap(); - // TODO: Populate the scores table with details extracted from the - // current line. Keep in mind that goals scored by team_1 - // will be the number of goals conceded from team_2, and similarly - // goals scored by team_2 will be the number of goals conceded by - // team_1. - } - scores -} - -#[cfg(test)] -mod tests { - use super::*; - - fn get_results() -> String { - let results = "".to_string() - + "England,France,4,2\n" - + "France,Italy,3,1\n" - + "Poland,Spain,2,0\n" - + "Germany,England,2,1\n"; - results - } - - #[test] - fn build_scores() { - let scores = build_scores_table(get_results()); - - let mut keys: Vec<&String> = scores.keys().collect(); - keys.sort(); - assert_eq!( - keys, - vec!["England", "France", "Germany", "Italy", "Poland", "Spain"] - ); - } - - #[test] - fn validate_team_score_1() { - let scores = build_scores_table(get_results()); - let team = scores.get("England").unwrap(); - assert_eq!(team.goals_scored, 5); - assert_eq!(team.goals_conceded, 4); - } - - #[test] - fn validate_team_score_2() { - let scores = build_scores_table(get_results()); - let team = scores.get("Spain").unwrap(); - assert_eq!(team.goals_scored, 0); - assert_eq!(team.goals_conceded, 2); - } -} diff --git a/exercises/if/README.md b/exercises/if/README.md deleted file mode 100644 index b52c392..0000000 --- a/exercises/if/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# If - -`if`, the most basic (but still surprisingly versatile!) type of control flow, is what you'll learn here. - -## Further information - -- [Control Flow - if expressions](https://doc.rust-lang.org/book/ch03-05-control-flow.html#if-expressions) diff --git a/exercises/if/if1.rs b/exercises/if/if1.rs deleted file mode 100644 index 4734d78..0000000 --- a/exercises/if/if1.rs +++ /dev/null @@ -1,33 +0,0 @@ -// 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 -} - -// Don't mind this for now :) -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ten_is_bigger_than_eight() { - assert_eq!(10, bigger(10, 8)); - } - - #[test] - fn fortytwo_is_bigger_than_thirtytwo() { - assert_eq!(42, bigger(32, 42)); - } - - #[test] - fn equal_numbers() { - assert_eq!(42, bigger(42, 42)); - } -} diff --git a/exercises/if/if2.rs b/exercises/if/if2.rs deleted file mode 100644 index f512f13..0000000 --- a/exercises/if/if2.rs +++ /dev/null @@ -1,37 +0,0 @@ -// if2.rs -// -// Step 1: Make me compile! -// 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 { - 1 - } -} - -// No test changes needed! -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn foo_for_fizz() { - assert_eq!(foo_if_fizz("fizz"), "foo") - } - - #[test] - fn bar_for_fuzz() { - assert_eq!(foo_if_fizz("fuzz"), "bar") - } - - #[test] - fn default_to_baz() { - assert_eq!(foo_if_fizz("literally anything"), "baz") - } -} diff --git a/exercises/if/if3.rs b/exercises/if/if3.rs deleted file mode 100644 index 1696274..0000000 --- a/exercises/if/if3.rs +++ /dev/null @@ -1,56 +0,0 @@ -// if3.rs -// -// Execute `rustlings hint if3` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -pub fn animal_habitat(animal: &str) -> &'static str { - let identifier = if animal == "crab" { - 1 - } else if animal == "gopher" { - 2.0 - } else if animal == "snake" { - 3 - } else { - "Unknown" - }; - - // DO NOT CHANGE THIS STATEMENT BELOW - let habitat = if identifier == 1 { - "Beach" - } else if identifier == 2 { - "Burrow" - } else if identifier == 3 { - "Desert" - } else { - "Unknown" - }; - - habitat -} - -// No test changes needed. -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn gopher_lives_in_burrow() { - assert_eq!(animal_habitat("gopher"), "Burrow") - } - - #[test] - fn snake_lives_in_desert() { - assert_eq!(animal_habitat("snake"), "Desert") - } - - #[test] - fn crab_lives_on_beach() { - assert_eq!(animal_habitat("crab"), "Beach") - } - - #[test] - fn unknown_animal() { - assert_eq!(animal_habitat("dinosaur"), "Unknown") - } -} diff --git a/exercises/intro/README.md b/exercises/intro/README.md deleted file mode 100644 index d32e4a8..0000000 --- a/exercises/intro/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Intro - -Rust uses the `print!` and `println!` macros to print text to the console. - -## Further information - -- [Hello World](https://doc.rust-lang.org/rust-by-example/hello.html) -- [Formatted print](https://doc.rust-lang.org/rust-by-example/hello/print.html) diff --git a/exercises/intro/intro1.rs b/exercises/intro/intro1.rs deleted file mode 100644 index 37fa011..0000000 --- a/exercises/intro/intro1.rs +++ /dev/null @@ -1,41 +0,0 @@ -// intro1.rs -// -// About this `I AM NOT DONE` thing: -// We sometimes encourage you to keep trying things on a given exercise, even -// after you already figured it out. If you got everything working and feel -// ready for the next exercise, remove the `I AM NOT DONE` comment below. -// -// If you're running this using `rustlings watch`: The exercise file will be -// reloaded 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! -// -// Execute `rustlings hint intro1` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - println!("Hello and"); - println!(r#" welcome to... "#); - println!(r#" _ _ _ "#); - println!(r#" _ __ _ _ ___| |_| (_)_ __ __ _ ___ "#); - println!(r#" | '__| | | / __| __| | | '_ \ / _` / __| "#); - println!(r#" | | | |_| \__ \ |_| | | | | | (_| \__ \ "#); - println!(r#" |_| \__,_|___/\__|_|_|_| |_|\__, |___/ "#); - println!(r#" |___/ "#); - println!(); - println!("This exercise compiles successfully. The remaining exercises contain a compiler"); - println!("or logic error. The central concept behind Rustlings is to fix these errors and"); - 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!(); - println!( - "If you want to use rust-analyzer, Rust's LSP implementation, make sure your editor is set" - ); - println!("up, and then run `rustlings lsp` before continuing.") -} diff --git a/exercises/intro/intro2.rs b/exercises/intro/intro2.rs deleted file mode 100644 index 990b20f..0000000 --- a/exercises/intro/intro2.rs +++ /dev/null @@ -1,12 +0,0 @@ -// intro2.rs -// -// 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 {}!"); -} diff --git a/exercises/iterators/README.md b/exercises/iterators/README.md deleted file mode 100644 index 0e8b671..0000000 --- a/exercises/iterators/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Iterators - -This section will teach you about Iterators. - -## Further information - -- [Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) -- [Iterator documentation](https://doc.rust-lang.org/stable/std/iter/) diff --git a/exercises/iterators/iterators1.rs b/exercises/iterators/iterators1.rs deleted file mode 100644 index 31076bb..0000000 --- a/exercises/iterators/iterators1.rs +++ /dev/null @@ -1,26 +0,0 @@ -// iterators1.rs -// -// When performing operations on elements within a collection, iterators are -// essential. This module helps you get familiar with the structure of using an -// iterator and how to go through elements within an iterable collection. -// -// Make me compile by filling in the `???`s -// -// Execute `rustlings hint iterators1` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -#[test] -fn main() { - let my_fav_fruits = vec!["banana", "custard apple", "avocado", "peach", "raspberry"]; - - let mut my_iterable_fav_fruits = ???; // 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(&"avocado")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 3 - assert_eq!(my_iterable_fav_fruits.next(), Some(&"raspberry")); - assert_eq!(my_iterable_fav_fruits.next(), ???); // TODO: Step 4 -} diff --git a/exercises/iterators/iterators2.rs b/exercises/iterators/iterators2.rs deleted file mode 100644 index dda82a0..0000000 --- a/exercises/iterators/iterators2.rs +++ /dev/null @@ -1,63 +0,0 @@ -// iterators2.rs -// -// In this exercise, you'll learn some of the unique advantages that iterators -// 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" -pub fn capitalize_first(input: &str) -> String { - let mut c = input.chars(); - match c.next() { - None => String::new(), - Some(first) => ???, - } -} - -// Step 2. -// Apply the `capitalize_first` function to a slice of string slices. -// Return a vector of strings. -// ["hello", "world"] -> ["Hello", "World"] -pub fn capitalize_words_vector(words: &[&str]) -> Vec { - vec![] -} - -// Step 3. -// Apply the `capitalize_first` function again to a slice of string slices. -// Return a single string. -// ["hello", " ", "world"] -> "Hello World" -pub fn capitalize_words_string(words: &[&str]) -> String { - String::new() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_success() { - assert_eq!(capitalize_first("hello"), "Hello"); - } - - #[test] - fn test_empty() { - assert_eq!(capitalize_first(""), ""); - } - - #[test] - fn test_iterate_string_vec() { - let words = vec!["hello", "world"]; - assert_eq!(capitalize_words_vector(&words), ["Hello", "World"]); - } - - #[test] - fn test_iterate_into_string() { - let words = vec!["hello", " ", "world"]; - assert_eq!(capitalize_words_string(&words), "Hello World"); - } -} diff --git a/exercises/iterators/iterators3.rs b/exercises/iterators/iterators3.rs deleted file mode 100644 index 29fa23a..0000000 --- a/exercises/iterators/iterators3.rs +++ /dev/null @@ -1,90 +0,0 @@ -// iterators3.rs -// -// This is a bigger exercise than most of the others! You can do it! Here is -// your mission, should you choose to accept it: -// 1. Complete the divide function to get the first four tests to pass. -// 2. Get the remaining tests to pass by completing the result_with_list and -// 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), - DivideByZero, -} - -#[derive(Debug, PartialEq, Eq)] -pub struct NotDivisibleError { - dividend: i32, - divisor: i32, -} - -// 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!(); -} - -// 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() -> () { - let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); -} - -// 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() -> () { - let numbers = vec![27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_success() { - assert_eq!(divide(81, 9), Ok(9)); - } - - #[test] - fn test_not_divisible() { - assert_eq!( - divide(81, 6), - Err(DivisionError::NotDivisible(NotDivisibleError { - dividend: 81, - divisor: 6 - })) - ); - } - - #[test] - fn test_divide_by_0() { - assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); - } - - #[test] - fn test_divide_0_by_something() { - assert_eq!(divide(0, 81), Ok(0)); - } - - #[test] - fn test_result_with_list() { - assert_eq!(format!("{:?}", result_with_list()), "Ok([1, 11, 1426, 3])"); - } - - #[test] - fn test_list_of_results() { - assert_eq!( - format!("{:?}", list_of_results()), - "[Ok(1), Ok(11), Ok(1426), Ok(3)]" - ); - } -} diff --git a/exercises/iterators/iterators4.rs b/exercises/iterators/iterators4.rs deleted file mode 100644 index 79e1692..0000000 --- a/exercises/iterators/iterators4.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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: - // - return - // Try not to use: - // - imperative style loops (for, while) - // - additional variables - // For an extra challenge, don't use: - // - recursion - // Execute `rustlings hint iterators4` for hints. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn factorial_of_0() { - assert_eq!(1, factorial(0)); - } - - #[test] - fn factorial_of_1() { - assert_eq!(1, factorial(1)); - } - #[test] - fn factorial_of_2() { - assert_eq!(2, factorial(2)); - } - - #[test] - fn factorial_of_4() { - assert_eq!(24, factorial(4)); - } -} diff --git a/exercises/iterators/iterators5.rs b/exercises/iterators/iterators5.rs deleted file mode 100644 index a062ee4..0000000 --- a/exercises/iterators/iterators5.rs +++ /dev/null @@ -1,156 +0,0 @@ -// iterators5.rs -// -// Let's define a simple model to track Rustlings exercise progress. Progress -// will be modelled using a hash map. The name of the exercise is the key and -// the progress is the value. Two counting functions were created to count the -// number of exercises with a given progress. Recreate this counting -// functionality using iterators. Try not to use imperative loops (for, while). -// Only the two iterator methods (count_iterator and count_collection_iterator) -// need to be modified. -// -// Execute `rustlings hint iterators5` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -use std::collections::HashMap; - -#[derive(Clone, Copy, PartialEq, Eq)] -enum Progress { - None, - Some, - Complete, -} - -fn count_for(map: &HashMap, value: Progress) -> usize { - let mut count = 0; - for val in map.values() { - if val == &value { - count += 1; - } - } - count -} - -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!(); -} - -fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { - let mut count = 0; - for map in collection { - for val in map.values() { - if val == &value { - count += 1; - } - } - } - count -} - -fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { - // collection is a slice of hashmaps. - // collection = [{ "variables1": Complete, "from_str": None, ... }, - // { "variables2": Complete, ... }, ... ] - todo!(); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn count_complete() { - let map = get_map(); - assert_eq!(3, count_iterator(&map, Progress::Complete)); - } - - #[test] - fn count_some() { - let map = get_map(); - assert_eq!(1, count_iterator(&map, Progress::Some)); - } - - #[test] - fn count_none() { - let map = get_map(); - assert_eq!(2, count_iterator(&map, Progress::None)); - } - - #[test] - fn count_complete_equals_for() { - let map = get_map(); - let progress_states = vec![Progress::Complete, Progress::Some, Progress::None]; - for progress_state in progress_states { - assert_eq!( - count_for(&map, progress_state), - count_iterator(&map, progress_state) - ); - } - } - - #[test] - fn count_collection_complete() { - let collection = get_vec_map(); - assert_eq!( - 6, - count_collection_iterator(&collection, Progress::Complete) - ); - } - - #[test] - fn count_collection_some() { - let collection = get_vec_map(); - assert_eq!(1, count_collection_iterator(&collection, Progress::Some)); - } - - #[test] - fn count_collection_none() { - let collection = get_vec_map(); - assert_eq!(4, count_collection_iterator(&collection, Progress::None)); - } - - #[test] - fn count_collection_equals_for() { - let progress_states = vec![Progress::Complete, Progress::Some, Progress::None]; - let collection = get_vec_map(); - - for progress_state in progress_states { - assert_eq!( - count_collection_for(&collection, progress_state), - count_collection_iterator(&collection, progress_state) - ); - } - } - - fn get_map() -> HashMap { - use Progress::*; - - let mut map = HashMap::new(); - map.insert(String::from("variables1"), Complete); - map.insert(String::from("functions1"), Complete); - map.insert(String::from("hashmap1"), Complete); - map.insert(String::from("arc1"), Some); - map.insert(String::from("as_ref_mut"), None); - map.insert(String::from("from_str"), None); - - map - } - - fn get_vec_map() -> Vec> { - use Progress::*; - - let map = get_map(); - - let mut other = HashMap::new(); - other.insert(String::from("variables2"), Complete); - other.insert(String::from("functions2"), Complete); - other.insert(String::from("if1"), Complete); - other.insert(String::from("from_into"), None); - other.insert(String::from("try_from_into"), None); - - vec![map, other] - } -} diff --git a/exercises/lifetimes/README.md b/exercises/lifetimes/README.md deleted file mode 100644 index 91373f7..0000000 --- a/exercises/lifetimes/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Lifetimes - -Lifetimes tell the compiler how to check whether references live long -enough to be valid in any given situation. For example lifetimes say -"make sure parameter 'a' lives as long as parameter 'b' so that the return -value is valid". - -They are only necessary on borrows, i.e. references, -since copied parameters or moves are owned in their scope and cannot -be referenced outside. Lifetimes mean that calling code of e.g. functions -can be checked to make sure their arguments are valid. Lifetimes are -restrictive of their callers. - -If you'd like to learn more about lifetime annotations, the -[lifetimekata](https://tfpk.github.io/lifetimekata/) project -has a similar style of exercises to Rustlings, but is all about -learning to write lifetime annotations. - -## Further information - -- [Lifetimes (in Rust By Example)](https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime.html) -- [Validating References with Lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) diff --git a/exercises/lifetimes/lifetimes1.rs b/exercises/lifetimes/lifetimes1.rs deleted file mode 100644 index 87bde49..0000000 --- a/exercises/lifetimes/lifetimes1.rs +++ /dev/null @@ -1,27 +0,0 @@ -// lifetimes1.rs -// -// The Rust compiler needs to know how to check whether supplied references are -// valid, so that it can let the programmer know if a reference is at risk of -// going out of scope before it is used. Remember, references are borrows and do -// not own their own data. What if their owner goes out of scope? -// -// Execute `rustlings hint lifetimes1` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn longest(x: &str, y: &str) -> &str { - if x.len() > y.len() { - x - } else { - y - } -} - -fn main() { - let string1 = String::from("abcd"); - let string2 = "xyz"; - - let result = longest(string1.as_str(), string2); - println!("The longest string is '{}'", result); -} diff --git a/exercises/lifetimes/lifetimes2.rs b/exercises/lifetimes/lifetimes2.rs deleted file mode 100644 index 4f3d8c1..0000000 --- a/exercises/lifetimes/lifetimes2.rs +++ /dev/null @@ -1,27 +0,0 @@ -// lifetimes2.rs -// -// So if the compiler is just validating the references passed to the annotated -// parameters and the return type, what do we need to change? -// -// 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 - } else { - y - } -} - -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()); - } - println!("The longest string is '{}'", result); -} diff --git a/exercises/lifetimes/lifetimes3.rs b/exercises/lifetimes/lifetimes3.rs deleted file mode 100644 index 9c59f9c..0000000 --- a/exercises/lifetimes/lifetimes3.rs +++ /dev/null @@ -1,21 +0,0 @@ -// lifetimes3.rs -// -// Lifetimes are also needed when structs hold references. -// -// Execute `rustlings hint lifetimes3` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -struct Book { - author: &str, - title: &str, -} - -fn main() { - let name = String::from("Jill Smith"); - let title = String::from("Fish Flying"); - let book = Book { author: &name, title: &title }; - - println!("{} by {}", book.title, book.author); -} diff --git a/exercises/macros/README.md b/exercises/macros/README.md deleted file mode 100644 index 337816d..0000000 --- a/exercises/macros/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Macros - -Rust's macro system is very powerful, but also kind of difficult to wrap your -head around. We're not going to teach you how to write your own fully-featured -macros. Instead, we'll show you how to use and create them. - -If you'd like to learn more about writing your own macros, the -[macrokata](https://github.com/tfpk/macrokata) project has a similar style -of exercises to Rustlings, but is all about learning to write Macros. - -## Further information - -- [Macros](https://doc.rust-lang.org/book/ch19-06-macros.html) -- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) diff --git a/exercises/macros/macros1.rs b/exercises/macros/macros1.rs deleted file mode 100644 index 678de6e..0000000 --- a/exercises/macros/macros1.rs +++ /dev/null @@ -1,16 +0,0 @@ -// 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!"); - }; -} - -fn main() { - my_macro(); -} diff --git a/exercises/macros/macros2.rs b/exercises/macros/macros2.rs deleted file mode 100644 index 788fc16..0000000 --- a/exercises/macros/macros2.rs +++ /dev/null @@ -1,16 +0,0 @@ -// 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!"); - }; -} diff --git a/exercises/macros/macros3.rs b/exercises/macros/macros3.rs deleted file mode 100644 index b795c14..0000000 --- a/exercises/macros/macros3.rs +++ /dev/null @@ -1,20 +0,0 @@ -// macros3.rs -// -// 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 - -mod macros { - macro_rules! my_macro { - () => { - println!("Check out my macro!"); - }; - } -} - -fn main() { - my_macro!(); -} diff --git a/exercises/macros/macros4.rs b/exercises/macros/macros4.rs deleted file mode 100644 index 71b45a0..0000000 --- a/exercises/macros/macros4.rs +++ /dev/null @@ -1,21 +0,0 @@ -// macros4.rs -// -// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -#[rustfmt::skip] -macro_rules! my_macro { - () => { - println!("Check out my macro!"); - } - ($val:expr) => { - println!("Look at this other macro: {}", $val); - } -} - -fn main() { - my_macro!(); - my_macro!(7777); -} diff --git a/exercises/modules/README.md b/exercises/modules/README.md deleted file mode 100644 index 3dc8a48..0000000 --- a/exercises/modules/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Modules - -In this section we'll give you an introduction to Rust's module system. - -## Further information - -- [The Module System](https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) diff --git a/exercises/modules/modules1.rs b/exercises/modules/modules1.rs deleted file mode 100644 index 9eb5a48..0000000 --- a/exercises/modules/modules1.rs +++ /dev/null @@ -1,22 +0,0 @@ -// 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() { - get_secret_recipe(); - println!("sausage!"); - } -} - -fn main() { - sausage_factory::make_sausage(); -} diff --git a/exercises/modules/modules2.rs b/exercises/modules/modules2.rs deleted file mode 100644 index 0415454..0000000 --- a/exercises/modules/modules2.rs +++ /dev/null @@ -1,34 +0,0 @@ -// modules2.rs -// -// You can bring module paths into scopes and provide new names for them with -// the '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 ??? - - mod fruits { - pub const PEAR: &'static str = "Pear"; - pub const APPLE: &'static str = "Apple"; - } - - mod veggies { - pub const CUCUMBER: &'static str = "Cucumber"; - pub const CARROT: &'static str = "Carrot"; - } -} - -fn main() { - println!( - "favorite snacks: {} and {}", - delicious_snacks::fruit, - delicious_snacks::veggie - ); -} diff --git a/exercises/modules/modules3.rs b/exercises/modules/modules3.rs deleted file mode 100644 index f2bb050..0000000 --- a/exercises/modules/modules3.rs +++ /dev/null @@ -1,21 +0,0 @@ -// modules3.rs -// -// You can use the 'use' keyword to bring module paths from modules from -// anywhere and especially from the Rust standard library into your scope. Bring -// SystemTime and UNIX_EPOCH 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 ??? - -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/move_semantics/README.md b/exercises/move_semantics/README.md deleted file mode 100644 index 54ddd8e..0000000 --- a/exercises/move_semantics/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Move Semantics - -These exercises are adapted from [pnkfelix](https://github.com/pnkfelix)'s [Rust Tutorial](https://pnkfelix.github.io/rust-examples-icfp2014/) -- Thank you Felix!!! - -## Further information - -For this section, the book links are especially important. - -- [Ownership](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html) -- [Reference and borrowing](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html) diff --git a/exercises/move_semantics/move_semantics1.rs b/exercises/move_semantics/move_semantics1.rs deleted file mode 100644 index e063937..0000000 --- a/exercises/move_semantics/move_semantics1.rs +++ /dev/null @@ -1,23 +0,0 @@ -// move_semantics1.rs -// -// Execute `rustlings hint move_semantics1` or use the `hint` watch subcommand -// for a hint. - -// I AM NOT DONE - -#[test] -fn main() { - let vec0 = vec![22, 44, 66]; - - let vec1 = fill_vec(vec0); - - assert_eq!(vec1, vec![22, 44, 66, 88]); -} - -fn fill_vec(vec: Vec) -> Vec { - let vec = vec; - - vec.push(88); - - vec -} diff --git a/exercises/move_semantics/move_semantics2.rs b/exercises/move_semantics/move_semantics2.rs deleted file mode 100644 index baf6bcc..0000000 --- a/exercises/move_semantics/move_semantics2.rs +++ /dev/null @@ -1,26 +0,0 @@ -// move_semantics2.rs -// -// Make the test pass by finding a way to keep both Vecs separate! -// -// Execute `rustlings hint move_semantics2` or use the `hint` watch subcommand -// for a hint. - -// I AM NOT DONE - -#[test] -fn main() { - let vec0 = vec![22, 44, 66]; - - let mut vec1 = fill_vec(vec0); - - assert_eq!(vec0, vec![22, 44, 66]); - assert_eq!(vec1, vec![22, 44, 66, 88]); -} - -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - - vec.push(88); - - vec -} diff --git a/exercises/move_semantics/move_semantics3.rs b/exercises/move_semantics/move_semantics3.rs deleted file mode 100644 index 7af9e69..0000000 --- a/exercises/move_semantics/move_semantics3.rs +++ /dev/null @@ -1,24 +0,0 @@ -// move_semantics3.rs -// -// Make me compile without adding new lines -- just changing existing lines! (no -// lines with multiple semicolons necessary!) -// -// Execute `rustlings hint move_semantics3` or use the `hint` watch subcommand -// for a hint. - -// I AM NOT DONE - -#[test] -fn main() { - let vec0 = vec![22, 44, 66]; - - let mut vec1 = fill_vec(vec0); - - assert_eq!(vec1, vec![22, 44, 66, 88]); -} - -fn fill_vec(vec: Vec) -> Vec { - vec.push(88); - - vec -} diff --git a/exercises/move_semantics/move_semantics4.rs b/exercises/move_semantics/move_semantics4.rs deleted file mode 100644 index 80b49db..0000000 --- a/exercises/move_semantics/move_semantics4.rs +++ /dev/null @@ -1,29 +0,0 @@ -// move_semantics4.rs -// -// Refactor this code so that instead of passing `vec0` into the `fill_vec` -// function, the Vector gets created in the function itself and passed back to -// the main function. -// -// Execute `rustlings hint move_semantics4` or use the `hint` watch subcommand -// for a hint. - -// I AM NOT DONE - -#[test] -fn main() { - let vec0 = vec![22, 44, 66]; - - let mut vec1 = fill_vec(vec0); - - assert_eq!(vec1, vec![22, 44, 66, 88]); -} - -// `fill_vec()` no longer takes `vec: Vec` as argument - don't change this! -fn fill_vec() -> Vec { - // Instead, let's create and fill the Vec in here - how do you do that? - let mut vec = vec; - - vec.push(88); - - vec -} diff --git a/exercises/move_semantics/move_semantics5.rs b/exercises/move_semantics/move_semantics5.rs deleted file mode 100644 index 267bdcc..0000000 --- a/exercises/move_semantics/move_semantics5.rs +++ /dev/null @@ -1,19 +0,0 @@ -// move_semantics5.rs -// -// Make me compile only by reordering the lines in `main()`, but without 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 - -#[test] -fn main() { - let mut x = 100; - let y = &mut x; - let z = &mut x; - *y += 100; - *z += 1000; - assert_eq!(x, 1200); -} diff --git a/exercises/move_semantics/move_semantics6.rs b/exercises/move_semantics/move_semantics6.rs deleted file mode 100644 index cace4ca..0000000 --- a/exercises/move_semantics/move_semantics6.rs +++ /dev/null @@ -1,28 +0,0 @@ -// move_semantics6.rs -// -// You can't change anything except adding or removing references. -// -// Execute `rustlings hint move_semantics6` or use the `hint` watch subcommand -// for a hint. - -// I AM NOT DONE - -fn main() { - let data = "Rust is great!".to_string(); - - get_char(data); - - string_uppercase(&data); -} - -// Should not take ownership -fn get_char(data: String) -> char { - data.chars().last().unwrap() -} - -// Should take ownership -fn string_uppercase(mut data: &String) { - data = &data.to_uppercase(); - - println!("{}", data); -} diff --git a/exercises/options/README.md b/exercises/options/README.md deleted file mode 100644 index bdd3374..0000000 --- a/exercises/options/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Options - -Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. -Option types are very common in Rust code, as they have a number of uses: - -- Initial values -- Return values for functions that are not defined over their entire input range (partial functions) -- Return value for otherwise reporting simple errors, where None is returned on error -- Optional struct fields -- Struct fields that can be loaned or "taken" -- Optional function arguments -- Nullable pointers -- Swapping things out of difficult situations - -## Further Information - -- [Option Enum Format](https://doc.rust-lang.org/stable/book/ch10-01-syntax.html#in-enum-definitions) -- [Option Module Documentation](https://doc.rust-lang.org/std/option/) -- [Option Enum Documentation](https://doc.rust-lang.org/std/option/enum.Option.html) -- [if let](https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html) -- [while let](https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html) diff --git a/exercises/options/options1.rs b/exercises/options/options1.rs deleted file mode 100644 index e131b48..0000000 --- a/exercises/options/options1.rs +++ /dev/null @@ -1,39 +0,0 @@ -// 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 :( -fn maybe_icecream(time_of_day: u16) -> Option { - // We use the 24-hour system here, so 10PM is a value of 22 and 12AM is a - // value of 0 The Option output should gracefully handle cases where - // time_of_day > 23. - // TODO: Complete the function body - remember to return an Option! - ??? -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn check_icecream() { - assert_eq!(maybe_icecream(9), Some(5)); - assert_eq!(maybe_icecream(10), Some(5)); - assert_eq!(maybe_icecream(23), Some(0)); - assert_eq!(maybe_icecream(22), Some(0)); - assert_eq!(maybe_icecream(25), None); - } - - #[test] - fn raw_value() { - // TODO: Fix this test. How do you get at the value contained in the - // Option? - let icecreams = maybe_icecream(12); - assert_eq!(icecreams, 5); - } -} diff --git a/exercises/options/options2.rs b/exercises/options/options2.rs deleted file mode 100644 index 4d998e7..0000000 --- a/exercises/options/options2.rs +++ /dev/null @@ -1,42 +0,0 @@ -// options2.rs -// -// Execute `rustlings hint options2` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -#[cfg(test)] -mod tests { - #[test] - fn simple_option() { - let target = "rustlings"; - let optional_target = Some(target); - - // TODO: Make this an if let statement whose value is "Some" type - word = optional_target { - assert_eq!(word, target); - } - } - - #[test] - fn layered_option() { - let range = 10; - let mut optional_integers: Vec> = vec![None]; - - for i in 1..(range + 1) { - optional_integers.push(Some(i)); - } - - let mut cursor = range; - - // 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() { - assert_eq!(integer, cursor); - cursor -= 1; - } - - assert_eq!(cursor, 0); - } -} diff --git a/exercises/options/options3.rs b/exercises/options/options3.rs deleted file mode 100644 index 23c15ea..0000000 --- a/exercises/options/options3.rs +++ /dev/null @@ -1,21 +0,0 @@ -// 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, -} - -fn main() { - let y: Option = Some(Point { x: 100, y: 200 }); - - match y { - Some(p) => println!("Co-ordinates are {},{} ", p.x, p.y), - _ => panic!("no match!"), - } - y; // Fix without deleting this line. -} diff --git a/exercises/primitive_types/README.md b/exercises/primitive_types/README.md deleted file mode 100644 index cea69b0..0000000 --- a/exercises/primitive_types/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Primitive Types - -Rust has a couple of basic types that are directly implemented into the -compiler. In this section, we'll go through the most important ones. - -## Further information - -- [Data Types](https://doc.rust-lang.org/stable/book/ch03-02-data-types.html) -- [The Slice Type](https://doc.rust-lang.org/stable/book/ch04-03-slices.html) diff --git a/exercises/primitive_types/primitive_types1.rs b/exercises/primitive_types/primitive_types1.rs deleted file mode 100644 index 3663340..0000000 --- a/exercises/primitive_types/primitive_types1.rs +++ /dev/null @@ -1,20 +0,0 @@ -// primitive_types1.rs -// -// 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`) - - let is_morning = true; - if is_morning { - println!("Good morning!"); - } - - let // 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 deleted file mode 100644 index f1616ed..0000000 --- a/exercises/primitive_types/primitive_types2.rs +++ /dev/null @@ -1,32 +0,0 @@ -// primitive_types2.rs -// -// 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`) - - // Note the _single_ quotes, these are different from the double quotes - // you've been seeing around. - let my_first_initial = 'C'; - if my_first_initial.is_alphabetic() { - println!("Alphabetical!"); - } else if my_first_initial.is_numeric() { - println!("Numerical!"); - } else { - 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! - if your_character.is_alphabetic() { - println!("Alphabetical!"); - } else if your_character.is_numeric() { - println!("Numerical!"); - } else { - println!("Neither alphabetic nor numeric!"); - } -} diff --git a/exercises/primitive_types/primitive_types3.rs b/exercises/primitive_types/primitive_types3.rs deleted file mode 100644 index 8b0de44..0000000 --- a/exercises/primitive_types/primitive_types3.rs +++ /dev/null @@ -1,19 +0,0 @@ -// primitive_types3.rs -// -// 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 = ??? - - if a.len() >= 100 { - println!("Wow, that's a big array!"); - } else { - println!("Meh, I eat arrays like that for breakfast."); - panic!("Array not big enough, more elements needed") - } -} diff --git a/exercises/primitive_types/primitive_types4.rs b/exercises/primitive_types/primitive_types4.rs deleted file mode 100644 index d44d877..0000000 --- a/exercises/primitive_types/primitive_types4.rs +++ /dev/null @@ -1,17 +0,0 @@ -// primitive_types4.rs -// -// 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 = ??? - - assert_eq!([2, 3, 4], nice_slice) -} diff --git a/exercises/primitive_types/primitive_types5.rs b/exercises/primitive_types/primitive_types5.rs deleted file mode 100644 index f646986..0000000 --- a/exercises/primitive_types/primitive_types5.rs +++ /dev/null @@ -1,15 +0,0 @@ -// primitive_types5.rs -// -// 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; - - println!("{} is {} years old.", name, age); -} diff --git a/exercises/primitive_types/primitive_types6.rs b/exercises/primitive_types/primitive_types6.rs deleted file mode 100644 index 07cc46c..0000000 --- a/exercises/primitive_types/primitive_types6.rs +++ /dev/null @@ -1,19 +0,0 @@ -// primitive_types6.rs -// -// Use a tuple index to access the second element of `numbers`. 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 = ???; - - assert_eq!(2, second, - "This is not the 2nd number in the tuple!") -} diff --git a/exercises/smart_pointers/README.md b/exercises/smart_pointers/README.md deleted file mode 100644 index d56d2b6..0000000 --- a/exercises/smart_pointers/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Smart Pointers - -In Rust, smart pointers are variables that contain an address in memory and reference some other data, but they also have additional metadata and capabilities. -Smart pointers in Rust often own the data they point to, while references only borrow data. - -## Further Information - -- [Smart Pointers](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) -- [Using Box to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html) -- [Rc\, the Reference Counted Smart Pointer](https://doc.rust-lang.org/book/ch15-04-rc.html) -- [Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html) -- [Cow Documentation](https://doc.rust-lang.org/std/borrow/enum.Cow.html) diff --git a/exercises/smart_pointers/arc1.rs b/exercises/smart_pointers/arc1.rs deleted file mode 100644 index 3526ddc..0000000 --- a/exercises/smart_pointers/arc1.rs +++ /dev/null @@ -1,45 +0,0 @@ -// arc1.rs -// -// In this exercise, we are given a Vec of u32 called "numbers" with values -// ranging from 0 to 99 -- [ 0, 1, 2, ..., 98, 99 ] We would like to use this -// set of numbers within 8 different threads simultaneously. Each thread is -// going to get the sum of every eighth value, with an offset. -// -// The first thread (offset 0), will sum 0, 8, 16, ... -// The second thread (offset 1), will sum 1, 9, 17, ... -// The third thread (offset 2), will sum 2, 10, 18, ... -// ... -// The eighth thread (offset 7), will sum 7, 15, 23, ... -// -// 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 mut joinhandles = Vec::new(); - - for offset in 0..8 { - let child_numbers = // 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); - })); - } - for handle in joinhandles.into_iter() { - handle.join().unwrap(); - } -} diff --git a/exercises/smart_pointers/box1.rs b/exercises/smart_pointers/box1.rs deleted file mode 100644 index 513e7da..0000000 --- a/exercises/smart_pointers/box1.rs +++ /dev/null @@ -1,58 +0,0 @@ -// box1.rs -// -// At compile time, Rust needs to know how much space a type takes up. This -// becomes problematic for recursive types, where a value can have as part of -// itself another value of the same type. To get around the issue, we can use a -// `Box` - a smart pointer used to store data on the heap, which also allows us -// to wrap a recursive type. -// -// The recursive type we're implementing in this exercise is the `cons list` - a -// data structure frequently found in functional programming languages. Each -// item in a cons list contains two elements: the value of the current item and -// the next item. The last item is a value called `Nil`. -// -// Step 1: use a `Box` in the enum definition to make the code compile -// Step 2: create both empty and non-empty cons lists by replacing `todo!()` -// -// Note: the tests should not be changed -// -// 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), - Nil, -} - -fn main() { - println!("This is an empty cons list: {:?}", create_empty_list()); - println!( - "This is a non-empty cons list: {:?}", - create_non_empty_list() - ); -} - -pub fn create_empty_list() -> List { - todo!() -} - -pub fn create_non_empty_list() -> List { - todo!() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_create_empty_list() { - assert_eq!(List::Nil, create_empty_list()) - } - - #[test] - fn test_create_non_empty_list() { - assert_ne!(create_empty_list(), create_non_empty_list()) - } -} diff --git a/exercises/smart_pointers/cow1.rs b/exercises/smart_pointers/cow1.rs deleted file mode 100644 index fcd3e0b..0000000 --- a/exercises/smart_pointers/cow1.rs +++ /dev/null @@ -1,78 +0,0 @@ -// cow1.rs -// -// This exercise explores the Cow, or Clone-On-Write type. Cow is a -// clone-on-write smart pointer. 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. -// -// This exercise is meant to show you what to expect when passing data to Cow. -// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the -// TODO markers. -// -// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::borrow::Cow; - -fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> { - for i in 0..input.len() { - let v = input[i]; - if v < 0 { - // Clones into a vector if not already owned. - input.to_mut()[i] = -v; - } - } - input -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference_mutation() -> Result<(), &'static str> { - // Clone occurs because `input` needs to be mutated. - let slice = [-1, 0, 1]; - let mut input = Cow::from(&slice[..]); - match abs_all(&mut input) { - Cow::Owned(_) => Ok(()), - _ => Err("Expected owned value"), - } - } - - #[test] - fn reference_no_mutation() -> Result<(), &'static str> { - // No clone occurs because `input` doesn't need to be mutated. - let slice = [0, 1, 2]; - let mut input = Cow::from(&slice[..]); - match abs_all(&mut input) { - // TODO - } - } - - #[test] - fn owned_no_mutation() -> Result<(), &'static str> { - // We can also pass `slice` without `&` so Cow owns it directly. In this - // case no mutation occurs and thus also no clone, but the result is - // still owned because it was never borrowed or mutated. - let slice = vec![0, 1, 2]; - let mut input = Cow::from(slice); - match abs_all(&mut input) { - // TODO - } - } - - #[test] - fn owned_mutation() -> Result<(), &'static str> { - // Of course this is also the case if a mutation does occur. In this - // case the call to `to_mut()` in the abs_all() function returns a - // reference to the same data as before. - let slice = vec![-1, 0, 1]; - let mut input = Cow::from(slice); - match abs_all(&mut input) { - // TODO - } - } -} diff --git a/exercises/smart_pointers/rc1.rs b/exercises/smart_pointers/rc1.rs deleted file mode 100644 index 1b90346..0000000 --- a/exercises/smart_pointers/rc1.rs +++ /dev/null @@ -1,105 +0,0 @@ -// rc1.rs -// -// In this exercise, we want to express the concept of multiple owners via the -// Rc type. This is a model of our solar system - there is a Sun type and -// multiple Planets. The Planets take ownership of the sun, indicating that they -// revolve around the sun. -// -// Make this code compile by using the proper Rc primitives to express that the -// sun has multiple owners. -// -// Execute `rustlings hint rc1` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -use std::rc::Rc; - -#[derive(Debug)] -struct Sun {} - -#[derive(Debug)] -enum Planet { - Mercury(Rc), - Venus(Rc), - Earth(Rc), - Mars(Rc), - Jupiter(Rc), - Saturn(Rc), - Uranus(Rc), - Neptune(Rc), -} - -impl Planet { - fn details(&self) { - println!("Hi from {:?}!", self) - } -} - -#[test] -fn main() { - let sun = Rc::new(Sun {}); - println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference - - let mercury = Planet::Mercury(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - mercury.details(); - - let venus = Planet::Venus(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - venus.details(); - - let earth = Planet::Earth(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 4 references - earth.details(); - - let mars = Planet::Mars(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 5 references - mars.details(); - - let jupiter = Planet::Jupiter(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 6 references - jupiter.details(); - - // TODO - let saturn = Planet::Saturn(Rc::new(Sun {})); - println!("reference count = {}", Rc::strong_count(&sun)); // 7 references - saturn.details(); - - // TODO - let uranus = Planet::Uranus(Rc::new(Sun {})); - println!("reference count = {}", Rc::strong_count(&sun)); // 8 references - uranus.details(); - - // TODO - let neptune = Planet::Neptune(Rc::new(Sun {})); - println!("reference count = {}", Rc::strong_count(&sun)); // 9 references - neptune.details(); - - assert_eq!(Rc::strong_count(&sun), 9); - - drop(neptune); - println!("reference count = {}", Rc::strong_count(&sun)); // 8 references - - drop(uranus); - println!("reference count = {}", Rc::strong_count(&sun)); // 7 references - - drop(saturn); - println!("reference count = {}", Rc::strong_count(&sun)); // 6 references - - drop(jupiter); - println!("reference count = {}", Rc::strong_count(&sun)); // 5 references - - drop(mars); - println!("reference count = {}", Rc::strong_count(&sun)); // 4 references - - // TODO - println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - - // TODO - println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - - // TODO - println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference - - assert_eq!(Rc::strong_count(&sun), 1); -} diff --git a/exercises/strings/README.md b/exercises/strings/README.md deleted file mode 100644 index fa2104c..0000000 --- a/exercises/strings/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Strings - -Rust has two string types, a string slice (`&str`) and an owned string (`String`). -We're not going to dictate when you should use which one, but we'll show you how -to identify and create them, as well as use them. - -## Further information - -- [Strings](https://doc.rust-lang.org/book/ch08-02-strings.html) diff --git a/exercises/strings/strings1.rs b/exercises/strings/strings1.rs deleted file mode 100644 index f50e1fa..0000000 --- a/exercises/strings/strings1.rs +++ /dev/null @@ -1,17 +0,0 @@ -// strings1.rs -// -// 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" -} diff --git a/exercises/strings/strings2.rs b/exercises/strings/strings2.rs deleted file mode 100644 index 4d95d16..0000000 --- a/exercises/strings/strings2.rs +++ /dev/null @@ -1,21 +0,0 @@ -// strings2.rs -// -// 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) { - println!("That is a color word I know!"); - } else { - println!("That is not a color word I know."); - } -} - -fn is_a_color_word(attempt: &str) -> bool { - attempt == "green" || attempt == "blue" || attempt == "red" -} diff --git a/exercises/strings/strings3.rs b/exercises/strings/strings3.rs deleted file mode 100644 index b29f932..0000000 --- a/exercises/strings/strings3.rs +++ /dev/null @@ -1,45 +0,0 @@ -// 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! - ??? -} - -fn compose_me(input: &str) -> String { - // TODO: Add " world!" to the string! There's multiple ways to do this! - ??? -} - -fn replace_me(input: &str) -> String { - // TODO: Replace "cars" in the string with "balloons"! - ??? -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn trim_a_string() { - assert_eq!(trim_me("Hello! "), "Hello!"); - assert_eq!(trim_me(" What's up!"), "What's up!"); - assert_eq!(trim_me(" Hola! "), "Hola!"); - } - - #[test] - fn compose_a_string() { - assert_eq!(compose_me("Hello"), "Hello world!"); - assert_eq!(compose_me("Goodbye"), "Goodbye world!"); - } - - #[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"); - } -} diff --git a/exercises/strings/strings4.rs b/exercises/strings/strings4.rs deleted file mode 100644 index e8c54ac..0000000 --- a/exercises/strings/strings4.rs +++ /dev/null @@ -1,30 +0,0 @@ -// strings4.rs -// -// Ok, here are a bunch of values-- some are `String`s, some are `&str`s. Your -// task is to call one of these two functions on each value depending on what -// you think each value is. That is, add either `string_slice` or `string` -// before the parentheses on each line. If you're right, it will compile! -// -// No hints this time! - -// I AM NOT DONE - -fn string_slice(arg: &str) { - println!("{}", arg); -} -fn string(arg: String) { - println!("{}", arg); -} - -fn main() { - ???("blue"); - ???("red".to_string()); - ???(String::from("hi")); - ???("rust is fun!".to_owned()); - ???("nice weather".into()); - ???(format!("Interpolation {}", "Station")); - ???(&String::from("abc")[0..1]); - ???(" hello there ".trim()); - ???("Happy Monday!".to_string().replace("Mon", "Tues")); - ???("mY sHiFt KeY iS sTiCkY".to_lowercase()); -} diff --git a/exercises/structs/README.md b/exercises/structs/README.md deleted file mode 100644 index 3fc1fdc..0000000 --- a/exercises/structs/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Structs - -Rust has three struct types: a classic C struct, a tuple struct, and a unit struct. - -## Further information - -- [Structures](https://doc.rust-lang.org/book/ch05-01-defining-structs.html) -- [Method Syntax](https://doc.rust-lang.org/book/ch05-03-method-syntax.html) diff --git a/exercises/structs/structs1.rs b/exercises/structs/structs1.rs deleted file mode 100644 index 5fa5821..0000000 --- a/exercises/structs/structs1.rs +++ /dev/null @@ -1,51 +0,0 @@ -// structs1.rs -// -// 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 -} - -struct ColorTupleStruct(/* TODO: Something goes here */); - -#[derive(Debug)] -struct UnitLikeStruct; - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn classic_c_structs() { - // TODO: Instantiate a classic c struct! - // let green = - - assert_eq!(green.red, 0); - assert_eq!(green.green, 255); - assert_eq!(green.blue, 0); - } - - #[test] - fn tuple_structs() { - // TODO: Instantiate a tuple struct! - // let green = - - assert_eq!(green.0, 0); - assert_eq!(green.1, 255); - assert_eq!(green.2, 0); - } - - #[test] - fn unit_structs() { - // TODO: Instantiate a unit-like struct! - // let unit_like_struct = - 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 deleted file mode 100644 index 328567f..0000000 --- a/exercises/structs/structs2.rs +++ /dev/null @@ -1,50 +0,0 @@ -// structs2.rs -// -// 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, - year: u32, - made_by_phone: bool, - made_by_mobile: bool, - made_by_email: bool, - item_number: u32, - count: u32, -} - -fn create_order_template() -> Order { - Order { - name: String::from("Bob"), - year: 2019, - made_by_phone: false, - made_by_mobile: false, - made_by_email: true, - item_number: 123, - count: 0, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn your_order() { - let order_template = create_order_template(); - // TODO: Create your own order using the update syntax and template above! - // let your_order = - 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); - assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile); - assert_eq!(your_order.made_by_email, order_template.made_by_email); - assert_eq!(your_order.item_number, order_template.item_number); - assert_eq!(your_order.count, 1); - } -} diff --git a/exercises/structs/structs3.rs b/exercises/structs/structs3.rs deleted file mode 100644 index 7cda5af..0000000 --- a/exercises/structs/structs3.rs +++ /dev/null @@ -1,88 +0,0 @@ -// structs3.rs -// -// Structs contain data, but can also have logic. In this exercise we have -// defined the Package struct and we want to test some logic attached to it. -// 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, - recipient_country: String, - weight_in_grams: u32, -} - -impl Package { - fn new(sender_country: String, recipient_country: String, weight_in_grams: u32) -> Package { - if weight_in_grams < 10 { - // This is not how you should handle errors in Rust, - // but we will learn about error handling later. - panic!("Can not ship a package with weight below 10 grams.") - } else { - Package { - sender_country, - recipient_country, - weight_in_grams, - } - } - } - - fn is_international(&self) -> ??? { - // Something goes here... - } - - fn get_fees(&self, cents_per_gram: u32) -> ??? { - // Something goes here... - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - #[should_panic] - fn fail_creating_weightless_package() { - let sender_country = String::from("Spain"); - let recipient_country = String::from("Austria"); - - Package::new(sender_country, recipient_country, 5); - } - - #[test] - fn create_international_package() { - let sender_country = String::from("Spain"); - let recipient_country = String::from("Russia"); - - let package = Package::new(sender_country, recipient_country, 1200); - - assert!(package.is_international()); - } - - #[test] - fn create_local_package() { - let sender_country = String::from("Canada"); - let recipient_country = sender_country.clone(); - - let package = Package::new(sender_country, recipient_country, 1200); - - assert!(!package.is_international()); - } - - #[test] - fn calculate_transport_fees() { - let sender_country = String::from("Spain"); - let recipient_country = String::from("Spain"); - - let cents_per_gram = 3; - - let package = Package::new(sender_country, recipient_country, 1500); - - assert_eq!(package.get_fees(cents_per_gram), 4500); - assert_eq!(package.get_fees(cents_per_gram * 2), 9000); - } -} diff --git a/exercises/tests/README.md b/exercises/tests/README.md deleted file mode 100644 index 27c6818..0000000 --- a/exercises/tests/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Tests - -Going out of order from the book to cover tests -- many of the following exercises will ask you to make tests pass! - -## Further information - -- [Writing Tests](https://doc.rust-lang.org/book/ch11-01-writing-tests.html) diff --git a/exercises/tests/tests1.rs b/exercises/tests/tests1.rs deleted file mode 100644 index 810277a..0000000 --- a/exercises/tests/tests1.rs +++ /dev/null @@ -1,21 +0,0 @@ -// tests1.rs -// -// Tests are important to ensure that your code does what you think it should -// do. Tests can be run on this file with the following command: rustlings run -// tests1 -// -// This test has a problem with it -- make the test compile! Make the test 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!(); - } -} diff --git a/exercises/tests/tests2.rs b/exercises/tests/tests2.rs deleted file mode 100644 index f8024e9..0000000 --- a/exercises/tests/tests2.rs +++ /dev/null @@ -1,17 +0,0 @@ -// tests2.rs -// -// This test has a problem with it -- make the test compile! Make the test 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!(); - } -} diff --git a/exercises/tests/tests3.rs b/exercises/tests/tests3.rs deleted file mode 100644 index 4013e38..0000000 --- a/exercises/tests/tests3.rs +++ /dev/null @@ -1,29 +0,0 @@ -// tests3.rs -// -// This test isn't testing our function -- make it do that in such a way that -// the test passes. Then write a second test that tests whether we get the -// result 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 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_true_when_even() { - assert!(); - } - - #[test] - fn is_false_when_odd() { - assert!(); - } -} diff --git a/exercises/tests/tests4.rs b/exercises/tests/tests4.rs deleted file mode 100644 index 935d0db..0000000 --- a/exercises/tests/tests4.rs +++ /dev/null @@ -1,48 +0,0 @@ -// tests4.rs -// -// Make sure that we're testing for the correct conditions! -// -// Execute `rustlings hint tests4` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -struct Rectangle { - width: i32, - height: i32 -} - -impl Rectangle { - // Only change the test functions themselves - pub fn new(width: i32, height: i32) -> Self { - if width <= 0 || height <= 0 { - panic!("Rectangle width and height cannot be negative!") - } - Rectangle {width, height} - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn correct_width_and_height() { - // This test should check if the rectangle is the size that we pass into its constructor - let rect = Rectangle::new(10, 20); - assert_eq!(???, 10); // check width - assert_eq!(???, 20); // check height - } - - #[test] - fn negative_width() { - // This test should check if program panics when we try to create rectangle with negative width - let _rect = Rectangle::new(-10, 10); - } - - #[test] - fn negative_height() { - // This test should check if program panics when we try to create rectangle with negative height - let _rect = Rectangle::new(10, -10); - } -} diff --git a/exercises/threads/README.md b/exercises/threads/README.md deleted file mode 100644 index dbe6664..0000000 --- a/exercises/threads/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Threads - -In most current operating systems, an executed program's code is run in a process, and the operating system manages multiple processes at once. -Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. - -## Further information - -- [Dining Philosophers example](https://doc.rust-lang.org/1.4.0/book/dining-philosophers.html) -- [Using Threads to Run Code Simultaneously](https://doc.rust-lang.org/book/ch16-01-threads.html) diff --git a/exercises/threads/threads1.rs b/exercises/threads/threads1.rs deleted file mode 100644 index 80b6def..0000000 --- a/exercises/threads/threads1.rs +++ /dev/null @@ -1,40 +0,0 @@ -// threads1.rs -// -// This program spawns multiple threads that each run for at least 250ms, and -// each thread returns how much time they took to complete. The program should -// wait until all the spawned threads have finished and should collect their -// return values into a vector. -// -// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -use std::thread; -use std::time::{Duration, Instant}; - -fn main() { - let mut handles = vec![]; - for i in 0..10 { - handles.push(thread::spawn(move || { - let start = Instant::now(); - thread::sleep(Duration::from_millis(250)); - println!("thread {} is complete", i); - start.elapsed().as_millis() - })); - } - - let mut results: Vec = vec![]; - for handle in handles { - // TODO: a struct is returned from thread::spawn, can you use it? - } - - if results.len() != 10 { - panic!("Oh no! All the spawned threads did not finish!"); - } - - println!(); - for (i, result) in results.into_iter().enumerate() { - println!("thread {} took {}ms", i, result); - } -} diff --git a/exercises/threads/threads2.rs b/exercises/threads/threads2.rs deleted file mode 100644 index 62dad80..0000000 --- a/exercises/threads/threads2.rs +++ /dev/null @@ -1,39 +0,0 @@ -// threads2.rs -// -// 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 -// -// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -use std::sync::Arc; -use std::thread; -use std::time::Duration; - -struct JobStatus { - jobs_completed: u32, -} - -fn main() { - let status = Arc::new(JobStatus { jobs_completed: 0 }); - let mut handles = vec![]; - for _ in 0..10 { - let status_shared = Arc::clone(&status); - 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; - }); - handles.push(handle); - } - for handle in handles { - 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 {}", ???); - } -} diff --git a/exercises/threads/threads3.rs b/exercises/threads/threads3.rs deleted file mode 100644 index 91006bb..0000000 --- a/exercises/threads/threads3.rs +++ /dev/null @@ -1,67 +0,0 @@ -// 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; -use std::time::Duration; - -struct Queue { - length: u32, - first_half: Vec, - second_half: Vec, -} - -impl Queue { - fn new() -> Self { - Queue { - length: 10, - first_half: vec![1, 2, 3, 4, 5], - second_half: vec![6, 7, 8, 9, 10], - } - } -} - -fn send_tx(q: Queue, tx: mpsc::Sender) -> () { - let qc = Arc::new(q); - let qc1 = Arc::clone(&qc); - let qc2 = Arc::clone(&qc); - - thread::spawn(move || { - for val in &qc1.first_half { - println!("sending {:?}", val); - tx.send(*val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } - }); - - thread::spawn(move || { - for val in &qc2.second_half { - println!("sending {:?}", val); - tx.send(*val).unwrap(); - thread::sleep(Duration::from_secs(1)); - } - }); -} - -#[test] -fn main() { - let (tx, rx) = mpsc::channel(); - let queue = Queue::new(); - let queue_length = queue.length; - - send_tx(queue, tx); - - let mut total_received: u32 = 0; - for received in rx { - println!("Got: {}", received); - total_received += 1; - } - - println!("total numbers received: {}", total_received); - assert_eq!(total_received, queue_length) -} diff --git a/exercises/traits/README.md b/exercises/traits/README.md deleted file mode 100644 index ac87c64..0000000 --- a/exercises/traits/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# Traits - -A trait is a collection of methods. - -Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the `String` data type implements the `From<&str>` trait. This allows a user to write `String::from("hello")`. - -In this way, traits are somewhat similar to Java interfaces and C++ abstract classes. - -Some additional common Rust traits include: - -- `Clone` (the `clone` method) -- `Display` (which allows formatted display via `{}`) -- `Debug` (which allows formatted display via `{:?}`) - -Because traits indicate shared behavior between data types, they are useful when writing generics. - -## Further information - -- [Traits](https://doc.rust-lang.org/book/ch10-02-traits.html) diff --git a/exercises/traits/traits1.rs b/exercises/traits/traits1.rs deleted file mode 100644 index 37dfcbf..0000000 --- a/exercises/traits/traits1.rs +++ /dev/null @@ -1,42 +0,0 @@ -// traits1.rs -// -// Time to implement some traits! Your task is to implement the trait -// `AppendBar` for the type `String`. The trait AppendBar has only one function, -// which appends "Bar" to any object 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 { - // TODO: Implement `AppendBar` for type `String`. -} - -fn main() { - let s = String::from("Foo"); - let s = s.append_bar(); - println!("s: {}", s); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_foo_bar() { - assert_eq!(String::from("Foo").append_bar(), String::from("FooBar")); - } - - #[test] - fn is_bar_bar() { - assert_eq!( - String::from("").append_bar().append_bar(), - String::from("BarBar") - ); - } -} diff --git a/exercises/traits/traits2.rs b/exercises/traits/traits2.rs deleted file mode 100644 index 3e35f8e..0000000 --- a/exercises/traits/traits2.rs +++ /dev/null @@ -1,29 +0,0 @@ -// traits2.rs -// -// Your task is to implement the trait `AppendBar` for a vector of strings. To -// implement this trait, consider for a moment what it means to 'append "Bar"' -// to a vector of strings. -// -// No boiler plate code this time, 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: Implement trait `AppendBar` for a vector of strings. - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_vec_pop_eq_bar() { - let mut foo = vec![String::from("Foo")].append_bar(); - assert_eq!(foo.pop().unwrap(), String::from("Bar")); - assert_eq!(foo.pop().unwrap(), String::from("Foo")); - } -} diff --git a/exercises/traits/traits3.rs b/exercises/traits/traits3.rs deleted file mode 100644 index 4e2b06b..0000000 --- a/exercises/traits/traits3.rs +++ /dev/null @@ -1,42 +0,0 @@ -// traits3.rs -// -// Your task is to implement the Licensed trait for both structures and have -// them return the same information without writing the same function twice. -// -// 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; -} - -struct SomeSoftware { - version_number: i32, -} - -struct OtherSoftware { - version_number: String, -} - -impl Licensed for SomeSoftware {} // Don't edit this line -impl Licensed for OtherSoftware {} // Don't edit this line - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_licensing_info_the_same() { - let licensing_info = String::from("Some information"); - let some_software = SomeSoftware { version_number: 1 }; - let other_software = OtherSoftware { - version_number: "v2.0.0".to_string(), - }; - assert_eq!(some_software.licensing_info(), licensing_info); - assert_eq!(other_software.licensing_info(), licensing_info); - } -} diff --git a/exercises/traits/traits4.rs b/exercises/traits/traits4.rs deleted file mode 100644 index 4bda3e5..0000000 --- a/exercises/traits/traits4.rs +++ /dev/null @@ -1,49 +0,0 @@ -// traits4.rs -// -// Your task is to replace the '??' sections so the code compiles. -// -// 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() - } -} - -struct SomeSoftware {} - -struct OtherSoftware {} - -impl Licensed for SomeSoftware {} -impl Licensed for OtherSoftware {} - -// YOU MAY ONLY CHANGE THE NEXT LINE -fn compare_license_types(software: ??, software_two: ??) -> bool { - software.licensing_info() == software_two.licensing_info() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compare_license_information() { - let some_software = SomeSoftware {}; - let other_software = OtherSoftware {}; - - assert!(compare_license_types(some_software, other_software)); - } - - #[test] - fn compare_license_information_backwards() { - let some_software = SomeSoftware {}; - let other_software = OtherSoftware {}; - - assert!(compare_license_types(other_software, some_software)); - } -} diff --git a/exercises/traits/traits5.rs b/exercises/traits/traits5.rs deleted file mode 100644 index df18380..0000000 --- a/exercises/traits/traits5.rs +++ /dev/null @@ -1,40 +0,0 @@ -// traits5.rs -// -// Your task is to replace the '??' sections so the code compiles. -// -// 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 - } -} - -pub trait OtherTrait { - fn other_function(&self) -> bool { - true - } -} - -struct SomeStruct {} -struct OtherStruct {} - -impl SomeTrait for SomeStruct {} -impl OtherTrait for SomeStruct {} -impl SomeTrait for OtherStruct {} -impl OtherTrait for OtherStruct {} - -// YOU MAY ONLY CHANGE THE NEXT LINE -fn some_func(item: ??) -> bool { - item.some_function() && item.other_function() -} - -fn main() { - some_func(SomeStruct {}); - some_func(OtherStruct {}); -} diff --git a/exercises/variables/README.md b/exercises/variables/README.md deleted file mode 100644 index 7964ff2..0000000 --- a/exercises/variables/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# 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. -You can make them mutable by adding `mut` in front of the variable name. - -## Further information - -- [Variables and Mutability](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html) diff --git a/exercises/variables/variables1.rs b/exercises/variables/variables1.rs deleted file mode 100644 index b3e089a..0000000 --- a/exercises/variables/variables1.rs +++ /dev/null @@ -1,13 +0,0 @@ -// variables1.rs -// -// Make me compile! -// -// Execute `rustlings hint variables1` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - x = 5; - println!("x has the value {}", x); -} diff --git a/exercises/variables/variables2.rs b/exercises/variables/variables2.rs deleted file mode 100644 index e1c23ed..0000000 --- a/exercises/variables/variables2.rs +++ /dev/null @@ -1,15 +0,0 @@ -// variables2.rs -// -// Execute `rustlings hint variables2` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - let x; - if x == 10 { - println!("x is ten!"); - } else { - println!("x is not ten!"); - } -} diff --git a/exercises/variables/variables3.rs b/exercises/variables/variables3.rs deleted file mode 100644 index 86bed41..0000000 --- a/exercises/variables/variables3.rs +++ /dev/null @@ -1,11 +0,0 @@ -// variables3.rs -// -// Execute `rustlings hint variables3` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - let x: i32; - println!("Number {}", x); -} diff --git a/exercises/variables/variables4.rs b/exercises/variables/variables4.rs deleted file mode 100644 index 5394f39..0000000 --- a/exercises/variables/variables4.rs +++ /dev/null @@ -1,13 +0,0 @@ -// variables4.rs -// -// Execute `rustlings hint variables4` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -fn main() { - let 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 deleted file mode 100644 index a29b38b..0000000 --- a/exercises/variables/variables5.rs +++ /dev/null @@ -1,13 +0,0 @@ -// 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 - println!("Number plus two is : {}", number + 2); -} diff --git a/exercises/variables/variables6.rs b/exercises/variables/variables6.rs deleted file mode 100644 index 853183b..0000000 --- a/exercises/variables/variables6.rs +++ /dev/null @@ -1,11 +0,0 @@ -// variables6.rs -// -// Execute `rustlings hint variables6` or use the `hint` watch subcommand for a -// hint. - -// I AM NOT DONE - -const NUMBER = 3; -fn main() { - println!("Number {}", NUMBER); -} diff --git a/exercises/vecs/README.md b/exercises/vecs/README.md deleted file mode 100644 index 8ff9b85..0000000 --- a/exercises/vecs/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# Vectors - -Vectors are one of the most-used Rust data structures. In other programming -languages, they'd simply be called Arrays, but since Rust operates on a -bit of a lower level, an array in Rust is stored on the stack (meaning it -can't grow or shrink, and the size needs to be known at compile time), -and a Vector is stored in the heap (where these restrictions do not apply). - -Vectors are a bit of a later chapter in the book, but we think that they're -useful enough to talk about them a bit earlier. We shall be talking about -the other useful data structure, hash maps, later. - -## Further information - -- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/stable/book/ch08-01-vectors.html) -- [`iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut) -- [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map) diff --git a/exercises/vecs/vecs1.rs b/exercises/vecs/vecs1.rs deleted file mode 100644 index 65b7a7f..0000000 --- a/exercises/vecs/vecs1.rs +++ /dev/null @@ -1,28 +0,0 @@ -// vecs1.rs -// -// Your task is to create a `Vec` which holds the exact same elements as in the -// array `a`. -// -// 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 - - (a, v) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_array_and_vec_similarity() { - let (a, v) = array_and_vec(); - assert_eq!(a, v[..]); - } -} diff --git a/exercises/vecs/vecs2.rs b/exercises/vecs/vecs2.rs deleted file mode 100644 index e92c970..0000000 --- a/exercises/vecs/vecs2.rs +++ /dev/null @@ -1,50 +0,0 @@ -// vecs2.rs -// -// A Vec of even numbers is given. Your task is to complete the loop so that -// each number in the Vec is multiplied by 2. -// -// Make me pass the test! -// -// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint. - -// I AM NOT DONE - -fn vec_loop(mut v: Vec) -> Vec { - for element in v.iter_mut() { - // TODO: Fill this up so that each element in the Vec `v` is - // multiplied by 2. - ??? - } - - // At this point, `v` should be equal to [4, 8, 12, 16, 20]. - v -} - -fn vec_map(v: &Vec) -> Vec { - v.iter().map(|element| { - // TODO: Do the same thing as above - but instead of mutating the - // Vec, you can just return the new number! - ??? - }).collect() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_vec_loop() { - let v: Vec = (1..).filter(|x| x % 2 == 0).take(5).collect(); - let ans = vec_loop(v.clone()); - - assert_eq!(ans, v.iter().map(|x| x * 2).collect::>()); - } - - #[test] - fn test_vec_map() { - let v: Vec = (1..).filter(|x| x % 2 == 0).take(5).collect(); - let ans = vec_map(&v); - - assert_eq!(ans, v.iter().map(|x| x * 2).collect::>()); - } -} diff --git a/info.toml b/info.toml index 02599fc..bbfee14 100644 --- a/info.toml +++ b/info.toml @@ -2,15 +2,15 @@ [[exercises]] name = "intro1" -path = "exercises/intro/intro1.rs" +path = "exercises/00_intro/intro1.rs" mode = "compile" hint = """ -Remove the `I AM NOT DONE` comment in the `exercises/intro/intro1.rs` file +Remove the `I AM NOT DONE` comment in the `exercises/intro00/intro1.rs` file to move on to the next exercise.""" [[exercises]] name = "intro2" -path = "exercises/intro/intro2.rs" +path = "exercises/00_intro/intro2.rs" mode = "compile" hint = """ Add an argument after the format string.""" @@ -19,7 +19,7 @@ Add an argument after the format string.""" [[exercises]] name = "variables1" -path = "exercises/variables/variables1.rs" +path = "exercises/01_variables/variables1.rs" mode = "compile" hint = """ The declaration in the first line in the main function is missing a keyword @@ -27,7 +27,7 @@ that is needed in Rust to create a new variable binding.""" [[exercises]] name = "variables2" -path = "exercises/variables/variables2.rs" +path = "exercises/01_variables/variables2.rs" mode = "compile" hint = """ The compiler message is saying that Rust cannot infer the type that the @@ -46,7 +46,7 @@ What if `x` is the same type as `10`? What if it's a different type?""" [[exercises]] name = "variables3" -path = "exercises/variables/variables3.rs" +path = "exercises/01_variables/variables3.rs" mode = "compile" hint = """ Oops! In this exercise, we have a variable binding that we've created on in the @@ -60,7 +60,7 @@ programming language -- thankfully the Rust compiler has caught this for us!""" [[exercises]] name = "variables4" -path = "exercises/variables/variables4.rs" +path = "exercises/01_variables/variables4.rs" mode = "compile" hint = """ In Rust, variable bindings are immutable by default. But here we're trying @@ -69,7 +69,7 @@ a variable binding mutable instead.""" [[exercises]] name = "variables5" -path = "exercises/variables/variables5.rs" +path = "exercises/01_variables/variables5.rs" mode = "compile" hint = """ In `variables4` we already learned how to make an immutable variable mutable @@ -87,7 +87,7 @@ Try to solve this exercise afterwards using this technique.""" [[exercises]] name = "variables6" -path = "exercises/variables/variables6.rs" +path = "exercises/01_variables/variables6.rs" mode = "compile" hint = """ We know about variables and mutability, but there is another important type of @@ -107,7 +107,7 @@ https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#constants [[exercises]] name = "functions1" -path = "exercises/functions/functions1.rs" +path = "exercises/02_functions/functions1.rs" mode = "compile" hint = """ This main function is calling a function that it expects to exist, but the @@ -117,7 +117,7 @@ Sounds a lot like `main`, doesn't it?""" [[exercises]] name = "functions2" -path = "exercises/functions/functions2.rs" +path = "exercises/02_functions/functions2.rs" mode = "compile" hint = """ Rust requires that all parts of a function's signature have type annotations, @@ -125,7 +125,7 @@ but `call_me` is missing the type annotation of `num`.""" [[exercises]] name = "functions3" -path = "exercises/functions/functions3.rs" +path = "exercises/02_functions/functions3.rs" mode = "compile" hint = """ This time, the function *declaration* is okay, but there's something wrong @@ -137,7 +137,7 @@ DONE` comment.""" [[exercises]] name = "functions4" -path = "exercises/functions/functions4.rs" +path = "exercises/02_functions/functions4.rs" mode = "compile" hint = """ The error message points to the function `sale_price` and says it expects a type @@ -149,7 +149,7 @@ for the prices here, since they can't be negative? If so, kudos!""" [[exercises]] name = "functions5" -path = "exercises/functions/functions5.rs" +path = "exercises/02_functions/functions5.rs" mode = "compile" hint = """ This is a really common error that can be fixed by removing one character. @@ -168,7 +168,7 @@ They are not the same. There are two solutions: [[exercises]] name = "if1" -path = "exercises/if/if1.rs" +path = "exercises/03_if/if1.rs" mode = "test" hint = """ It's possible to do this in one line if you would like! @@ -184,7 +184,7 @@ Remember in Rust that: [[exercises]] name = "if2" -path = "exercises/if/if2.rs" +path = "exercises/03_if/if2.rs" mode = "test" hint = """ For that first compiler error, it's important in Rust that each conditional @@ -193,7 +193,7 @@ conditions checking different input values.""" [[exercises]] name = "if3" -path = "exercises/if/if3.rs" +path = "exercises/03_if/if3.rs" mode = "test" hint = """ In Rust, every arm of an `if` expression has to return the same type of value. @@ -211,19 +211,19 @@ hint = "No hints this time ;)" [[exercises]] name = "primitive_types1" -path = "exercises/primitive_types/primitive_types1.rs" +path = "exercises/04_primitive_types/primitive_types1.rs" mode = "compile" hint = "No hints this time ;)" [[exercises]] name = "primitive_types2" -path = "exercises/primitive_types/primitive_types2.rs" +path = "exercises/04_primitive_types/primitive_types2.rs" mode = "compile" hint = "No hints this time ;)" [[exercises]] name = "primitive_types3" -path = "exercises/primitive_types/primitive_types3.rs" +path = "exercises/04_primitive_types/primitive_types3.rs" mode = "compile" hint = """ There's a shorthand to initialize Arrays with a certain size that does not @@ -239,7 +239,7 @@ for `a.len() >= 100`?""" [[exercises]] name = "primitive_types4" -path = "exercises/primitive_types/primitive_types4.rs" +path = "exercises/04_primitive_types/primitive_types4.rs" mode = "test" hint = """ Take a look at the 'Understanding Ownership -> Slices -> Other Slices' section @@ -254,7 +254,7 @@ https://doc.rust-lang.org/nomicon/coercions.html""" [[exercises]] name = "primitive_types5" -path = "exercises/primitive_types/primitive_types5.rs" +path = "exercises/04_primitive_types/primitive_types5.rs" mode = "compile" hint = """ Take a look at the 'Data Types -> The Tuple Type' section of the book: @@ -267,7 +267,7 @@ of the tuple. You can do it!!""" [[exercises]] name = "primitive_types6" -path = "exercises/primitive_types/primitive_types6.rs" +path = "exercises/04_primitive_types/primitive_types6.rs" mode = "test" hint = """ While you could use a destructuring `let` for the tuple here, try @@ -280,7 +280,7 @@ Now you have another tool in your toolbox!""" [[exercises]] name = "vecs1" -path = "exercises/vecs/vecs1.rs" +path = "exercises/05_vecs/vecs1.rs" mode = "test" hint = """ In Rust, there are two ways to define a Vector. @@ -295,7 +295,7 @@ of the Rust book to learn more. [[exercises]] name = "vecs2" -path = "exercises/vecs/vecs2.rs" +path = "exercises/05_vecs/vecs2.rs" mode = "test" hint = """ In the first function we are looping over the Vector and getting a reference to @@ -318,7 +318,7 @@ What do you think is the more commonly used pattern under Rust developers? [[exercises]] name = "move_semantics1" -path = "exercises/move_semantics/move_semantics1.rs" +path = "exercises/06_move_semantics/move_semantics1.rs" mode = "test" hint = """ So you've got the "cannot borrow immutable local variable `vec` as mutable" @@ -332,7 +332,7 @@ happens!""" [[exercises]] name = "move_semantics2" -path = "exercises/move_semantics/move_semantics2.rs" +path = "exercises/06_move_semantics/move_semantics2.rs" mode = "test" hint = """ When running this exercise for the first time, you'll notice an error about @@ -353,7 +353,7 @@ try them all: [[exercises]] name = "move_semantics3" -path = "exercises/move_semantics/move_semantics3.rs" +path = "exercises/06_move_semantics/move_semantics3.rs" mode = "test" hint = """ The difference between this one and the previous ones is that the first line @@ -363,7 +363,7 @@ an existing binding to be a mutable binding instead of an immutable one :)""" [[exercises]] name = "move_semantics4" -path = "exercises/move_semantics/move_semantics4.rs" +path = "exercises/06_move_semantics/move_semantics4.rs" mode = "test" hint = """ Stop reading whenever you feel like you have enough direction :) Or try @@ -377,7 +377,7 @@ So the end goal is to: [[exercises]] name = "move_semantics5" -path = "exercises/move_semantics/move_semantics5.rs" +path = "exercises/06_move_semantics/move_semantics5.rs" mode = "test" hint = """ Carefully reason about the range in which each mutable reference is in @@ -389,7 +389,7 @@ https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#mutable-ref [[exercises]] name = "move_semantics6" -path = "exercises/move_semantics/move_semantics6.rs" +path = "exercises/06_move_semantics/move_semantics6.rs" mode = "compile" hint = """ To find the answer, you can consult the book section "References and Borrowing": @@ -410,7 +410,7 @@ Another hint: it has to do with the `&` character.""" [[exercises]] name = "structs1" -path = "exercises/structs/structs1.rs" +path = "exercises/07_structs/structs1.rs" mode = "test" hint = """ Rust has more than one type of struct. Three actually, all variants are used to @@ -430,7 +430,7 @@ https://doc.rust-lang.org/book/ch05-01-defining-structs.html""" [[exercises]] name = "structs2" -path = "exercises/structs/structs2.rs" +path = "exercises/07_structs/structs2.rs" mode = "test" hint = """ Creating instances of structs is easy, all you need to do is assign some values @@ -442,7 +442,7 @@ https://doc.rust-lang.org/stable/book/ch05-01-defining-structs.html#creating-ins [[exercises]] name = "structs3" -path = "exercises/structs/structs3.rs" +path = "exercises/07_structs/structs3.rs" mode = "test" hint = """ For `is_international`: What makes a package international? Seems related to @@ -458,13 +458,13 @@ https://doc.rust-lang.org/book/ch05-03-method-syntax.html""" [[exercises]] name = "enums1" -path = "exercises/enums/enums1.rs" +path = "exercises/08_enums/enums1.rs" mode = "compile" hint = "No hints this time ;)" [[exercises]] name = "enums2" -path = "exercises/enums/enums2.rs" +path = "exercises/08_enums/enums2.rs" mode = "compile" hint = """ You can create enumerations that have different variants with different types @@ -472,7 +472,7 @@ such as no data, anonymous structs, a single string, tuples, ...etc""" [[exercises]] name = "enums3" -path = "exercises/enums/enums3.rs" +path = "exercises/08_enums/enums3.rs" mode = "test" hint = """ As a first step, you can define enums to compile this code without errors. @@ -486,7 +486,7 @@ to get value in the variant.""" [[exercises]] name = "strings1" -path = "exercises/strings/strings1.rs" +path = "exercises/09_strings/strings1.rs" mode = "compile" hint = """ The `current_favorite_color` function is currently returning a string slice @@ -500,7 +500,7 @@ another way that uses the `From` trait.""" [[exercises]] name = "strings2" -path = "exercises/strings/strings2.rs" +path = "exercises/09_strings/strings2.rs" mode = "compile" hint = """ Yes, it would be really easy to fix this by just changing the value bound to @@ -515,7 +515,7 @@ https://doc.rust-lang.org/stable/book/ch15-02-deref.html#implicit-deref-coercion [[exercises]] name = "strings3" -path = "exercises/strings/strings3.rs" +path = "exercises/09_strings/strings3.rs" mode = "test" hint = """ There's tons of useful standard library functions for strings. Let's try and use some of them: @@ -526,7 +526,7 @@ the string slice into an owned string, which you can then freely extend.""" [[exercises]] name = "strings4" -path = "exercises/strings/strings4.rs" +path = "exercises/09_strings/strings4.rs" mode = "compile" hint = "No hints this time ;)" @@ -534,7 +534,7 @@ hint = "No hints this time ;)" [[exercises]] name = "modules1" -path = "exercises/modules/modules1.rs" +path = "exercises/10_modules/modules1.rs" mode = "compile" hint = """ Everything is private in Rust by default-- but there's a keyword we can use @@ -543,7 +543,7 @@ needs to be public.""" [[exercises]] name = "modules2" -path = "exercises/modules/modules2.rs" +path = "exercises/10_modules/modules2.rs" mode = "compile" hint = """ The delicious_snacks module is trying to present an external interface that is @@ -555,7 +555,7 @@ Learn more at https://doc.rust-lang.org/book/ch07-04-bringing-paths-into-scope-w [[exercises]] name = "modules3" -path = "exercises/modules/modules3.rs" +path = "exercises/10_modules/modules3.rs" mode = "compile" hint = """ `UNIX_EPOCH` and `SystemTime` are declared in the `std::time` module. Add a @@ -566,7 +566,7 @@ paths or the glob operator to bring these two in using only one line.""" [[exercises]] name = "hashmaps1" -path = "exercises/hashmaps/hashmaps1.rs" +path = "exercises/11_hashmaps/hashmaps1.rs" mode = "test" hint = """ Hint 1: Take a look at the return type of the function to figure out @@ -578,7 +578,7 @@ Hint 2: Number of fruits should be at least 5. And you have to put [[exercises]] name = "hashmaps2" -path = "exercises/hashmaps/hashmaps2.rs" +path = "exercises/11_hashmaps/hashmaps2.rs" mode = "test" hint = """ Use the `entry()` and `or_insert()` methods of `HashMap` to achieve this. @@ -587,7 +587,7 @@ Learn more at https://doc.rust-lang.org/stable/book/ch08-03-hash-maps.html#only- [[exercises]] name = "hashmaps3" -path = "exercises/hashmaps/hashmaps3.rs" +path = "exercises/11_hashmaps/hashmaps3.rs" mode = "test" hint = """ Hint 1: Use the `entry()` and `or_insert()` methods of `HashMap` to insert @@ -613,7 +613,7 @@ hint = "No hints this time ;)" [[exercises]] name = "options1" -path = "exercises/options/options1.rs" +path = "exercises/12_options/options1.rs" mode = "test" hint = """ Options can have a `Some` value, with an inner value, or a `None` value, @@ -625,7 +625,7 @@ it doesn't panic in your face later?""" [[exercises]] name = "options2" -path = "exercises/options/options2.rs" +path = "exercises/12_options/options2.rs" mode = "test" hint = """ Check out: @@ -642,7 +642,7 @@ Also see `Option::flatten` [[exercises]] name = "options3" -path = "exercises/options/options3.rs" +path = "exercises/12_options/options3.rs" mode = "compile" hint = """ The compiler says a partial move happened in the `match` statement. How can @@ -655,7 +655,7 @@ https://doc.rust-lang.org/std/keyword.ref.html""" [[exercises]] name = "errors1" -path = "exercises/error_handling/errors1.rs" +path = "exercises/13_error_handling/errors1.rs" mode = "test" hint = """ `Ok` and `Err` are the two variants of `Result`, so what the tests are saying @@ -671,7 +671,7 @@ To make this change, you'll need to: [[exercises]] name = "errors2" -path = "exercises/error_handling/errors2.rs" +path = "exercises/13_error_handling/errors2.rs" mode = "test" hint = """ One way to handle this is using a `match` statement on @@ -687,7 +687,7 @@ and give it a try!""" [[exercises]] name = "errors3" -path = "exercises/error_handling/errors3.rs" +path = "exercises/13_error_handling/errors3.rs" mode = "compile" hint = """ If other functions can return a `Result`, why shouldn't `main`? It's a fairly @@ -699,7 +699,7 @@ positive results.""" [[exercises]] name = "errors4" -path = "exercises/error_handling/errors4.rs" +path = "exercises/13_error_handling/errors4.rs" mode = "test" hint = """ `PositiveNonzeroInteger::new` is always creating a new instance and returning @@ -711,7 +711,7 @@ everything is... okay :)""" [[exercises]] name = "errors5" -path = "exercises/error_handling/errors5.rs" +path = "exercises/13_error_handling/errors5.rs" mode = "compile" hint = """ There are two different possible `Result` types produced within `main()`, which @@ -735,7 +735,7 @@ https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reen [[exercises]] name = "errors6" -path = "exercises/error_handling/errors6.rs" +path = "exercises/13_error_handling/errors6.rs" mode = "test" hint = """ This exercise uses a completed version of `PositiveNonzeroInteger` from @@ -757,7 +757,7 @@ https://doc.rust-lang.org/std/result/enum.Result.html#method.map_err""" [[exercises]] name = "generics1" -path = "exercises/generics/generics1.rs" +path = "exercises/14_generics/generics1.rs" mode = "compile" hint = """ Vectors in Rust make use of generics to create dynamically sized arrays of any @@ -767,7 +767,7 @@ You need to tell the compiler what type we are pushing onto this vector.""" [[exercises]] name = "generics2" -path = "exercises/generics/generics2.rs" +path = "exercises/14_generics/generics2.rs" mode = "test" hint = """ Currently we are wrapping only values of type `u32`. @@ -781,7 +781,7 @@ If you are still stuck https://doc.rust-lang.org/stable/book/ch10-01-syntax.html [[exercises]] name = "traits1" -path = "exercises/traits/traits1.rs" +path = "exercises/15_traits/traits1.rs" mode = "test" hint = """ A discussion about Traits in Rust can be found at: @@ -790,7 +790,7 @@ https://doc.rust-lang.org/book/ch10-02-traits.html [[exercises]] name = "traits2" -path = "exercises/traits/traits2.rs" +path = "exercises/15_traits/traits2.rs" mode = "test" hint = """ Notice how the trait takes ownership of `self`, and returns `Self`. @@ -803,7 +803,7 @@ the documentation at: https://doc.rust-lang.org/std/vec/struct.Vec.html""" [[exercises]] name = "traits3" -path = "exercises/traits/traits3.rs" +path = "exercises/15_traits/traits3.rs" mode = "test" hint = """ Traits can have a default implementation for functions. Structs that implement @@ -815,7 +815,7 @@ See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#def [[exercises]] name = "traits4" -path = "exercises/traits/traits4.rs" +path = "exercises/15_traits/traits4.rs" mode = "test" hint = """ Instead of using concrete types as parameters you can use traits. Try replacing @@ -826,7 +826,7 @@ See the documentation at: https://doc.rust-lang.org/book/ch10-02-traits.html#tra [[exercises]] name = "traits5" -path = "exercises/traits/traits5.rs" +path = "exercises/15_traits/traits5.rs" mode = "compile" hint = """ To ensure a parameter implements multiple traits use the '+ syntax'. Try @@ -851,7 +851,7 @@ You may also need this: `use std::fmt::Display;`.""" [[exercises]] name = "lifetimes1" -path = "exercises/lifetimes/lifetimes1.rs" +path = "exercises/16_lifetimes/lifetimes1.rs" mode = "compile" hint = """ Let the compiler guide you. Also take a look at the book if you need help: @@ -859,7 +859,7 @@ https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html""" [[exercises]] name = "lifetimes2" -path = "exercises/lifetimes/lifetimes2.rs" +path = "exercises/16_lifetimes/lifetimes2.rs" mode = "compile" hint = """ Remember that the generic lifetime `'a` will get the concrete lifetime that is @@ -873,7 +873,7 @@ inner block: [[exercises]] name = "lifetimes3" -path = "exercises/lifetimes/lifetimes3.rs" +path = "exercises/16_lifetimes/lifetimes3.rs" mode = "compile" hint = """ If you use a lifetime annotation in a struct's fields, where else does it need @@ -883,7 +883,7 @@ to be added?""" [[exercises]] name = "tests1" -path = "exercises/tests/tests1.rs" +path = "exercises/17_tests/tests1.rs" mode = "test" hint = """ You don't even need to write any code to test -- you can just test values and @@ -898,7 +898,7 @@ ones pass, and which ones fail :)""" [[exercises]] name = "tests2" -path = "exercises/tests/tests2.rs" +path = "exercises/17_tests/tests2.rs" mode = "test" hint = """ Like the previous exercise, you don't need to write any code to get this test @@ -911,7 +911,7 @@ argument comes first and which comes second!""" [[exercises]] name = "tests3" -path = "exercises/tests/tests3.rs" +path = "exercises/17_tests/tests3.rs" mode = "test" hint = """ You can call a function right where you're passing arguments to `assert!`. So @@ -922,7 +922,7 @@ what you're doing using `!`, like `assert!(!having_fun())`.""" [[exercises]] name = "tests4" -path = "exercises/tests/tests4.rs" +path = "exercises/17_tests/tests4.rs" mode = "test" hint = """ We expect method `Rectangle::new()` to panic for negative values. @@ -936,7 +936,7 @@ https://doc.rust-lang.org/stable/book/ch11-01-writing-tests.html#checking-for-pa [[exercises]] name = "iterators1" -path = "exercises/iterators/iterators1.rs" +path = "exercises/18_iterators/iterators1.rs" mode = "test" hint = """ Step 1: @@ -959,7 +959,7 @@ https://doc.rust-lang.org/std/iter/trait.Iterator.html for some ideas. [[exercises]] name = "iterators2" -path = "exercises/iterators/iterators2.rs" +path = "exercises/18_iterators/iterators2.rs" mode = "test" hint = """ Step 1: @@ -985,7 +985,7 @@ powerful and very general. Rust just needs to know the desired type.""" [[exercises]] name = "iterators3" -path = "exercises/iterators/iterators3.rs" +path = "exercises/18_iterators/iterators3.rs" mode = "test" hint = """ The `divide` function needs to return the correct error when even division is @@ -1004,7 +1004,7 @@ powerful! It can make the solution to this exercise infinitely easier.""" [[exercises]] name = "iterators4" -path = "exercises/iterators/iterators4.rs" +path = "exercises/18_iterators/iterators4.rs" mode = "test" hint = """ In an imperative language, you might write a `for` loop that updates a mutable @@ -1016,7 +1016,7 @@ Hint 2: Check out the `fold` and `rfold` methods!""" [[exercises]] name = "iterators5" -path = "exercises/iterators/iterators5.rs" +path = "exercises/18_iterators/iterators5.rs" mode = "test" hint = """ The documentation for the `std::iter::Iterator` trait contains numerous methods @@ -1035,7 +1035,7 @@ a different method that could make your code more compact than using `fold`.""" [[exercises]] name = "box1" -path = "exercises/smart_pointers/box1.rs" +path = "exercises/19_smart_pointers/box1.rs" mode = "test" hint = """ Step 1: @@ -1059,7 +1059,7 @@ definition and try other types! [[exercises]] name = "rc1" -path = "exercises/smart_pointers/rc1.rs" +path = "exercises/19_smart_pointers/rc1.rs" mode = "test" hint = """ This is a straightforward exercise to use the `Rc` type. Each `Planet` has @@ -1078,7 +1078,7 @@ See more at: https://doc.rust-lang.org/book/ch15-04-rc.html [[exercises]] name = "arc1" -path = "exercises/smart_pointers/arc1.rs" +path = "exercises/19_smart_pointers/arc1.rs" mode = "compile" hint = """ Make `shared_numbers` be an `Arc` from the numbers vector. Then, in order @@ -1096,7 +1096,7 @@ https://doc.rust-lang.org/stable/book/ch16-00-concurrency.html [[exercises]] name = "cow1" -path = "exercises/smart_pointers/cow1.rs" +path = "exercises/19_smart_pointers/cow1.rs" mode = "test" hint = """ If `Cow` already owns the data it doesn't need to clone it when `to_mut()` is @@ -1110,7 +1110,7 @@ on the `Cow` type. [[exercises]] name = "threads1" -path = "exercises/threads/threads1.rs" +path = "exercises/20_threads/threads1.rs" mode = "compile" hint = """ `JoinHandle` is a struct that is returned from a spawned thread: @@ -1128,7 +1128,7 @@ https://doc.rust-lang.org/std/thread/struct.JoinHandle.html [[exercises]] name = "threads2" -path = "exercises/threads/threads2.rs" +path = "exercises/20_threads/threads2.rs" mode = "compile" hint = """ `Arc` is an Atomic Reference Counted pointer that allows safe, shared access @@ -1158,7 +1158,7 @@ what you've learned :)""" [[exercises]] name = "threads3" -path = "exercises/threads/threads3.rs" +path = "exercises/20_threads/threads3.rs" mode = "test" hint = """ An alternate way to handle concurrency between threads is to use an `mpsc` @@ -1177,7 +1177,7 @@ See https://doc.rust-lang.org/book/ch16-02-message-passing.html for more info. [[exercises]] name = "macros1" -path = "exercises/macros/macros1.rs" +path = "exercises/21_macros/macros1.rs" mode = "compile" hint = """ When you call a macro, you need to add something special compared to a @@ -1186,7 +1186,7 @@ regular function call. If you're stuck, take a look at what's inside [[exercises]] name = "macros2" -path = "exercises/macros/macros2.rs" +path = "exercises/21_macros/macros2.rs" mode = "compile" hint = """ Macros don't quite play by the same rules as the rest of Rust, in terms of @@ -1197,7 +1197,7 @@ Unlike other things in Rust, the order of "where you define a macro" versus [[exercises]] name = "macros3" -path = "exercises/macros/macros3.rs" +path = "exercises/21_macros/macros3.rs" mode = "compile" hint = """ In order to use a macro outside of its module, you need to do something @@ -1208,7 +1208,7 @@ exported macros, if you've seen any of those around.""" [[exercises]] name = "macros4" -path = "exercises/macros/macros4.rs" +path = "exercises/21_macros/macros4.rs" mode = "compile" hint = """ You only need to add a single character to make this compile. @@ -1225,7 +1225,7 @@ https://veykril.github.io/tlborm/""" [[exercises]] name = "clippy1" -path = "exercises/clippy/clippy1.rs" +path = "exercises/22_clippy/clippy1.rs" mode = "clippy" hint = """ Rust stores the highest precision version of any long or infinite precision @@ -1241,14 +1241,14 @@ appropriate replacement constant from `std::f32::consts`...""" [[exercises]] name = "clippy2" -path = "exercises/clippy/clippy2.rs" +path = "exercises/22_clippy/clippy2.rs" mode = "clippy" hint = """ `for` loops over `Option` values are more clearly expressed as an `if let`""" [[exercises]] name = "clippy3" -path = "exercises/clippy/clippy3.rs" +path = "exercises/22_clippy/clippy3.rs" mode = "clippy" hint = "No hints this time!" @@ -1256,7 +1256,7 @@ hint = "No hints this time!" [[exercises]] name = "using_as" -path = "exercises/conversions/using_as.rs" +path = "exercises/23_conversions/using_as.rs" mode = "test" hint = """ Use the `as` operator to cast one of the operands in the last line of the @@ -1264,14 +1264,14 @@ Use the `as` operator to cast one of the operands in the last line of the [[exercises]] name = "from_into" -path = "exercises/conversions/from_into.rs" +path = "exercises/23_conversions/from_into.rs" mode = "test" hint = """ Follow the steps provided right before the `From` implementation""" [[exercises]] name = "from_str" -path = "exercises/conversions/from_str.rs" +path = "exercises/23_conversions/from_str.rs" mode = "test" hint = """ The implementation of `FromStr` should return an `Ok` with a `Person` object, @@ -1292,7 +1292,7 @@ https://doc.rust-lang.org/stable/rust-by-example/error/multiple_error_types/reen [[exercises]] name = "try_from_into" -path = "exercises/conversions/try_from_into.rs" +path = "exercises/23_conversions/try_from_into.rs" mode = "test" hint = """ Follow the steps provided right before the `TryFrom` implementation. @@ -1315,7 +1315,7 @@ Challenge: Can you make the `TryFrom` implementations generic over many integer [[exercises]] name = "as_ref_mut" -path = "exercises/conversions/as_ref_mut.rs" +path = "exercises/23_conversions/as_ref_mut.rs" mode = "test" hint = """ Add `AsRef` or `AsMut` as a trait bound to the functions.""" -- cgit v1.2.3