From 4dfc11d74ab02ac5765ae5d08fb750c91f4744b4 Mon Sep 17 00:00:00 2001 From: Hunter Kvalevog Date: Fri, 2 Oct 2026 21:53:51 -0500 Subject: rustlings: move to rust/ --- rust/rustlings/.gitattributes | 2 + rust/rustlings/.gitignore | 3 + rust/rustlings/.rustlings-state.txt | 83 ++++++++ rust/rustlings/Cargo.toml | 222 +++++++++++++++++++++ rust/rustlings/exercises/00_intro/README.md | 8 + rust/rustlings/exercises/00_intro/intro1.rs | 28 +++ rust/rustlings/exercises/00_intro/intro2.rs | 3 + rust/rustlings/exercises/01_variables/README.md | 9 + .../rustlings/exercises/01_variables/variables1.rs | 5 + .../rustlings/exercises/01_variables/variables2.rs | 9 + .../rustlings/exercises/01_variables/variables3.rs | 5 + .../rustlings/exercises/01_variables/variables4.rs | 7 + .../rustlings/exercises/01_variables/variables5.rs | 7 + .../rustlings/exercises/01_variables/variables6.rs | 5 + rust/rustlings/exercises/02_functions/README.md | 8 + .../rustlings/exercises/02_functions/functions1.rs | 7 + .../rustlings/exercises/02_functions/functions2.rs | 9 + .../rustlings/exercises/02_functions/functions3.rs | 9 + .../rustlings/exercises/02_functions/functions4.rs | 17 ++ .../rustlings/exercises/02_functions/functions5.rs | 8 + rust/rustlings/exercises/03_if/README.md | 7 + rust/rustlings/exercises/03_if/if1.rs | 32 +++ rust/rustlings/exercises/03_if/if2.rs | 39 ++++ rust/rustlings/exercises/03_if/if3.rs | 52 +++++ .../exercises/04_primitive_types/README.md | 9 + .../04_primitive_types/primitive_types1.rs | 13 ++ .../04_primitive_types/primitive_types2.rs | 23 +++ .../04_primitive_types/primitive_types3.rs | 10 + .../04_primitive_types/primitive_types4.rs | 15 ++ .../04_primitive_types/primitive_types5.rs | 7 + .../04_primitive_types/primitive_types6.rs | 15 ++ rust/rustlings/exercises/05_vecs/README.md | 17 ++ rust/rustlings/exercises/05_vecs/vecs1.rs | 22 ++ rust/rustlings/exercises/05_vecs/vecs2.rs | 61 ++++++ .../exercises/06_move_semantics/README.md | 10 + .../exercises/06_move_semantics/move_semantics1.rs | 23 +++ .../exercises/06_move_semantics/move_semantics2.rs | 28 +++ .../exercises/06_move_semantics/move_semantics3.rs | 22 ++ .../exercises/06_move_semantics/move_semantics4.rs | 18 ++ .../exercises/06_move_semantics/move_semantics5.rs | 24 +++ rust/rustlings/exercises/07_structs/README.md | 8 + rust/rustlings/exercises/07_structs/structs1.rs | 50 +++++ rust/rustlings/exercises/07_structs/structs2.rs | 50 +++++ rust/rustlings/exercises/07_structs/structs3.rs | 84 ++++++++ rust/rustlings/exercises/08_enums/README.md | 10 + rust/rustlings/exercises/08_enums/enums1.rs | 16 ++ rust/rustlings/exercises/08_enums/enums2.rs | 40 ++++ rust/rustlings/exercises/08_enums/enums3.rs | 93 +++++++++ rust/rustlings/exercises/09_strings/README.md | 9 + rust/rustlings/exercises/09_strings/strings1.rs | 8 + rust/rustlings/exercises/09_strings/strings2.rs | 13 ++ rust/rustlings/exercises/09_strings/strings3.rs | 46 +++++ rust/rustlings/exercises/09_strings/strings4.rs | 37 ++++ rust/rustlings/exercises/10_modules/README.md | 7 + rust/rustlings/exercises/10_modules/modules1.rs | 15 ++ rust/rustlings/exercises/10_modules/modules2.rs | 26 +++ rust/rustlings/exercises/10_modules/modules3.rs | 13 ++ rust/rustlings/exercises/11_hashmaps/README.md | 12 ++ rust/rustlings/exercises/11_hashmaps/hashmaps1.rs | 43 ++++ rust/rustlings/exercises/11_hashmaps/hashmaps2.rs | 99 +++++++++ rust/rustlings/exercises/11_hashmaps/hashmaps3.rs | 84 ++++++++ rust/rustlings/exercises/12_options/README.md | 21 ++ rust/rustlings/exercises/12_options/options1.rs | 42 ++++ rust/rustlings/exercises/12_options/options2.rs | 39 ++++ rust/rustlings/exercises/12_options/options3.rs | 17 ++ .../exercises/13_error_handling/README.md | 12 ++ .../exercises/13_error_handling/errors1.rs | 40 ++++ .../exercises/13_error_handling/errors2.rs | 50 +++++ .../exercises/13_error_handling/errors3.rs | 33 +++ .../exercises/13_error_handling/errors4.rs | 44 ++++ .../exercises/13_error_handling/errors5.rs | 56 ++++++ .../exercises/13_error_handling/errors6.rs | 91 +++++++++ rust/rustlings/exercises/14_generics/README.md | 11 + rust/rustlings/exercises/14_generics/generics1.rs | 18 ++ rust/rustlings/exercises/14_generics/generics2.rs | 31 +++ rust/rustlings/exercises/15_traits/README.md | 19 ++ rust/rustlings/exercises/15_traits/traits1.rs | 33 +++ rust/rustlings/exercises/15_traits/traits2.rs | 30 +++ rust/rustlings/exercises/15_traits/traits3.rs | 40 ++++ rust/rustlings/exercises/15_traits/traits4.rs | 35 ++++ rust/rustlings/exercises/15_traits/traits5.rs | 39 ++++ rust/rustlings/exercises/16_lifetimes/README.md | 22 ++ .../rustlings/exercises/16_lifetimes/lifetimes1.rs | 28 +++ .../rustlings/exercises/16_lifetimes/lifetimes2.rs | 20 ++ .../rustlings/exercises/16_lifetimes/lifetimes3.rs | 16 ++ rust/rustlings/exercises/17_tests/README.md | 7 + rust/rustlings/exercises/17_tests/tests1.rs | 24 +++ rust/rustlings/exercises/17_tests/tests2.rs | 23 +++ rust/rustlings/exercises/17_tests/tests3.rs | 51 +++++ rust/rustlings/exercises/18_iterators/README.md | 8 + .../rustlings/exercises/18_iterators/iterators1.rs | 25 +++ .../rustlings/exercises/18_iterators/iterators2.rs | 63 ++++++ .../rustlings/exercises/18_iterators/iterators3.rs | 84 ++++++++ .../rustlings/exercises/18_iterators/iterators4.rs | 42 ++++ .../rustlings/exercises/18_iterators/iterators5.rs | 155 ++++++++++++++ .../exercises/19_smart_pointers/README.md | 12 ++ rust/rustlings/exercises/19_smart_pointers/arc1.rs | 45 +++++ rust/rustlings/exercises/19_smart_pointers/box1.rs | 50 +++++ rust/rustlings/exercises/19_smart_pointers/cow1.rs | 66 ++++++ rust/rustlings/exercises/19_smart_pointers/rc1.rs | 108 ++++++++++ rust/rustlings/exercises/20_threads/README.md | 10 + rust/rustlings/exercises/20_threads/threads1.rs | 37 ++++ rust/rustlings/exercises/20_threads/threads2.rs | 34 ++++ rust/rustlings/exercises/20_threads/threads3.rs | 60 ++++++ rust/rustlings/exercises/21_macros/README.md | 15 ++ rust/rustlings/exercises/21_macros/macros1.rs | 10 + rust/rustlings/exercises/21_macros/macros2.rs | 10 + rust/rustlings/exercises/21_macros/macros3.rs | 13 ++ rust/rustlings/exercises/21_macros/macros4.rs | 15 ++ rust/rustlings/exercises/22_clippy/README.md | 10 + rust/rustlings/exercises/22_clippy/clippy1.rs | 15 ++ rust/rustlings/exercises/22_clippy/clippy2.rs | 10 + rust/rustlings/exercises/22_clippy/clippy3.rs | 29 +++ rust/rustlings/exercises/23_conversions/README.md | 23 +++ .../exercises/23_conversions/as_ref_mut.rs | 62 ++++++ .../exercises/23_conversions/from_into.rs | 130 ++++++++++++ .../rustlings/exercises/23_conversions/from_str.rs | 113 +++++++++++ .../exercises/23_conversions/try_from_into.rs | 177 ++++++++++++++++ .../rustlings/exercises/23_conversions/using_as.rs | 24 +++ rust/rustlings/exercises/README.md | 27 +++ rust/rustlings/exercises/quizzes/README.md | 3 + rust/rustlings/exercises/quizzes/quiz1.rs | 35 ++++ rust/rustlings/exercises/quizzes/quiz2.rs | 81 ++++++++ rust/rustlings/exercises/quizzes/quiz3.rs | 64 ++++++ rust/rustlings/rust-analyzer.toml | 3 + rust/rustlings/solutions/00_intro/intro1.rs | 5 + rust/rustlings/solutions/00_intro/intro2.rs | 4 + .../rustlings/solutions/01_variables/variables1.rs | 6 + .../rustlings/solutions/01_variables/variables2.rs | 16 ++ .../rustlings/solutions/01_variables/variables3.rs | 15 ++ .../rustlings/solutions/01_variables/variables4.rs | 9 + .../rustlings/solutions/01_variables/variables5.rs | 9 + .../rustlings/solutions/01_variables/variables6.rs | 6 + .../rustlings/solutions/02_functions/functions1.rs | 8 + .../rustlings/solutions/02_functions/functions2.rs | 11 + .../rustlings/solutions/02_functions/functions3.rs | 10 + .../rustlings/solutions/02_functions/functions4.rs | 17 ++ .../rustlings/solutions/02_functions/functions5.rs | 9 + rust/rustlings/solutions/03_if/if1.rs | 28 +++ rust/rustlings/solutions/03_if/if2.rs | 35 ++++ rust/rustlings/solutions/03_if/if3.rs | 53 +++++ .../04_primitive_types/primitive_types1.rs | 11 + .../04_primitive_types/primitive_types2.rs | 21 ++ .../04_primitive_types/primitive_types3.rs | 11 + .../04_primitive_types/primitive_types4.rs | 23 +++ .../04_primitive_types/primitive_types5.rs | 8 + .../04_primitive_types/primitive_types6.rs | 16 ++ rust/rustlings/solutions/05_vecs/vecs1.rs | 23 +++ rust/rustlings/solutions/05_vecs/vecs2.rs | 55 +++++ .../solutions/06_move_semantics/move_semantics1.rs | 25 +++ .../solutions/06_move_semantics/move_semantics2.rs | 28 +++ .../solutions/06_move_semantics/move_semantics3.rs | 22 ++ .../solutions/06_move_semantics/move_semantics4.rs | 19 ++ .../solutions/06_move_semantics/move_semantics5.rs | 23 +++ rust/rustlings/solutions/07_structs/structs1.rs | 49 +++++ rust/rustlings/solutions/07_structs/structs2.rs | 51 +++++ rust/rustlings/solutions/07_structs/structs3.rs | 83 ++++++++ rust/rustlings/solutions/08_enums/enums1.rs | 16 ++ rust/rustlings/solutions/08_enums/enums2.rs | 37 ++++ rust/rustlings/solutions/08_enums/enums3.rs | 92 +++++++++ rust/rustlings/solutions/09_strings/strings1.rs | 9 + rust/rustlings/solutions/09_strings/strings2.rs | 15 ++ rust/rustlings/solutions/09_strings/strings3.rs | 49 +++++ rust/rustlings/solutions/09_strings/strings4.rs | 38 ++++ rust/rustlings/solutions/10_modules/modules1.rs | 15 ++ rust/rustlings/solutions/10_modules/modules2.rs | 23 +++ rust/rustlings/solutions/10_modules/modules3.rs | 8 + rust/rustlings/solutions/11_hashmaps/hashmaps1.rs | 42 ++++ rust/rustlings/solutions/11_hashmaps/hashmaps2.rs | 96 +++++++++ rust/rustlings/solutions/11_hashmaps/hashmaps3.rs | 85 ++++++++ rust/rustlings/solutions/12_options/options1.rs | 39 ++++ rust/rustlings/solutions/12_options/options2.rs | 37 ++++ rust/rustlings/solutions/12_options/options3.rs | 27 +++ .../solutions/13_error_handling/errors1.rs | 37 ++++ .../solutions/13_error_handling/errors2.rs | 58 ++++++ .../solutions/13_error_handling/errors3.rs | 32 +++ .../solutions/13_error_handling/errors4.rs | 42 ++++ .../solutions/13_error_handling/errors5.rs | 54 +++++ .../solutions/13_error_handling/errors6.rs | 106 ++++++++++ rust/rustlings/solutions/14_generics/generics1.rs | 17 ++ rust/rustlings/solutions/14_generics/generics2.rs | 28 +++ rust/rustlings/solutions/15_traits/traits1.rs | 32 +++ rust/rustlings/solutions/15_traits/traits2.rs | 27 +++ rust/rustlings/solutions/15_traits/traits3.rs | 36 ++++ rust/rustlings/solutions/15_traits/traits4.rs | 35 ++++ rust/rustlings/solutions/15_traits/traits5.rs | 39 ++++ .../rustlings/solutions/16_lifetimes/lifetimes1.rs | 24 +++ .../rustlings/solutions/16_lifetimes/lifetimes2.rs | 29 +++ .../rustlings/solutions/16_lifetimes/lifetimes3.rs | 18 ++ rust/rustlings/solutions/17_tests/tests1.rs | 24 +++ rust/rustlings/solutions/17_tests/tests2.rs | 22 ++ rust/rustlings/solutions/17_tests/tests3.rs | 45 +++++ .../rustlings/solutions/18_iterators/iterators1.rs | 26 +++ .../rustlings/solutions/18_iterators/iterators2.rs | 56 ++++++ .../rustlings/solutions/18_iterators/iterators3.rs | 88 ++++++++ .../rustlings/solutions/18_iterators/iterators4.rs | 72 +++++++ .../rustlings/solutions/18_iterators/iterators5.rs | 168 ++++++++++++++++ rust/rustlings/solutions/19_smart_pointers/arc1.rs | 45 +++++ rust/rustlings/solutions/19_smart_pointers/box1.rs | 47 +++++ rust/rustlings/solutions/19_smart_pointers/cow1.rs | 69 +++++++ rust/rustlings/solutions/19_smart_pointers/rc1.rs | 102 ++++++++++ rust/rustlings/solutions/20_threads/threads1.rs | 4 + rust/rustlings/solutions/20_threads/threads2.rs | 4 + rust/rustlings/solutions/20_threads/threads3.rs | 4 + rust/rustlings/solutions/21_macros/macros1.rs | 4 + rust/rustlings/solutions/21_macros/macros2.rs | 4 + rust/rustlings/solutions/21_macros/macros3.rs | 4 + rust/rustlings/solutions/21_macros/macros4.rs | 4 + rust/rustlings/solutions/22_clippy/clippy1.rs | 4 + rust/rustlings/solutions/22_clippy/clippy2.rs | 4 + rust/rustlings/solutions/22_clippy/clippy3.rs | 4 + .../solutions/23_conversions/as_ref_mut.rs | 4 + .../solutions/23_conversions/from_into.rs | 4 + .../rustlings/solutions/23_conversions/from_str.rs | 4 + .../solutions/23_conversions/try_from_into.rs | 4 + .../rustlings/solutions/23_conversions/using_as.rs | 4 + rust/rustlings/solutions/README.md | 6 + rust/rustlings/solutions/quizzes/quiz1.rs | 30 +++ rust/rustlings/solutions/quizzes/quiz2.rs | 90 +++++++++ rust/rustlings/solutions/quizzes/quiz3.rs | 65 ++++++ rustlings/.gitattributes | 2 - rustlings/.gitignore | 3 - rustlings/.rustlings-state.txt | 83 -------- rustlings/Cargo.toml | 222 --------------------- rustlings/exercises/00_intro/README.md | 8 - rustlings/exercises/00_intro/intro1.rs | 28 --- rustlings/exercises/00_intro/intro2.rs | 3 - rustlings/exercises/01_variables/README.md | 9 - rustlings/exercises/01_variables/variables1.rs | 5 - rustlings/exercises/01_variables/variables2.rs | 9 - rustlings/exercises/01_variables/variables3.rs | 5 - rustlings/exercises/01_variables/variables4.rs | 7 - rustlings/exercises/01_variables/variables5.rs | 7 - rustlings/exercises/01_variables/variables6.rs | 5 - rustlings/exercises/02_functions/README.md | 8 - rustlings/exercises/02_functions/functions1.rs | 7 - rustlings/exercises/02_functions/functions2.rs | 9 - rustlings/exercises/02_functions/functions3.rs | 9 - rustlings/exercises/02_functions/functions4.rs | 17 -- rustlings/exercises/02_functions/functions5.rs | 8 - rustlings/exercises/03_if/README.md | 7 - rustlings/exercises/03_if/if1.rs | 32 --- rustlings/exercises/03_if/if2.rs | 39 ---- rustlings/exercises/03_if/if3.rs | 52 ----- rustlings/exercises/04_primitive_types/README.md | 9 - .../04_primitive_types/primitive_types1.rs | 13 -- .../04_primitive_types/primitive_types2.rs | 23 --- .../04_primitive_types/primitive_types3.rs | 10 - .../04_primitive_types/primitive_types4.rs | 15 -- .../04_primitive_types/primitive_types5.rs | 7 - .../04_primitive_types/primitive_types6.rs | 15 -- rustlings/exercises/05_vecs/README.md | 17 -- rustlings/exercises/05_vecs/vecs1.rs | 22 -- rustlings/exercises/05_vecs/vecs2.rs | 61 ------ rustlings/exercises/06_move_semantics/README.md | 10 - .../exercises/06_move_semantics/move_semantics1.rs | 23 --- .../exercises/06_move_semantics/move_semantics2.rs | 28 --- .../exercises/06_move_semantics/move_semantics3.rs | 22 -- .../exercises/06_move_semantics/move_semantics4.rs | 18 -- .../exercises/06_move_semantics/move_semantics5.rs | 24 --- rustlings/exercises/07_structs/README.md | 8 - rustlings/exercises/07_structs/structs1.rs | 50 ----- rustlings/exercises/07_structs/structs2.rs | 50 ----- rustlings/exercises/07_structs/structs3.rs | 84 -------- rustlings/exercises/08_enums/README.md | 10 - rustlings/exercises/08_enums/enums1.rs | 16 -- rustlings/exercises/08_enums/enums2.rs | 40 ---- rustlings/exercises/08_enums/enums3.rs | 93 --------- rustlings/exercises/09_strings/README.md | 9 - rustlings/exercises/09_strings/strings1.rs | 8 - rustlings/exercises/09_strings/strings2.rs | 13 -- rustlings/exercises/09_strings/strings3.rs | 46 ----- rustlings/exercises/09_strings/strings4.rs | 37 ---- rustlings/exercises/10_modules/README.md | 7 - rustlings/exercises/10_modules/modules1.rs | 15 -- rustlings/exercises/10_modules/modules2.rs | 26 --- rustlings/exercises/10_modules/modules3.rs | 13 -- rustlings/exercises/11_hashmaps/README.md | 12 -- rustlings/exercises/11_hashmaps/hashmaps1.rs | 43 ---- rustlings/exercises/11_hashmaps/hashmaps2.rs | 99 --------- rustlings/exercises/11_hashmaps/hashmaps3.rs | 84 -------- rustlings/exercises/12_options/README.md | 21 -- rustlings/exercises/12_options/options1.rs | 42 ---- rustlings/exercises/12_options/options2.rs | 39 ---- rustlings/exercises/12_options/options3.rs | 17 -- rustlings/exercises/13_error_handling/README.md | 12 -- rustlings/exercises/13_error_handling/errors1.rs | 40 ---- rustlings/exercises/13_error_handling/errors2.rs | 50 ----- rustlings/exercises/13_error_handling/errors3.rs | 33 --- rustlings/exercises/13_error_handling/errors4.rs | 44 ---- rustlings/exercises/13_error_handling/errors5.rs | 56 ------ rustlings/exercises/13_error_handling/errors6.rs | 91 --------- rustlings/exercises/14_generics/README.md | 11 - rustlings/exercises/14_generics/generics1.rs | 18 -- rustlings/exercises/14_generics/generics2.rs | 31 --- rustlings/exercises/15_traits/README.md | 19 -- rustlings/exercises/15_traits/traits1.rs | 33 --- rustlings/exercises/15_traits/traits2.rs | 30 --- rustlings/exercises/15_traits/traits3.rs | 40 ---- rustlings/exercises/15_traits/traits4.rs | 35 ---- rustlings/exercises/15_traits/traits5.rs | 39 ---- rustlings/exercises/16_lifetimes/README.md | 22 -- rustlings/exercises/16_lifetimes/lifetimes1.rs | 28 --- rustlings/exercises/16_lifetimes/lifetimes2.rs | 20 -- rustlings/exercises/16_lifetimes/lifetimes3.rs | 16 -- rustlings/exercises/17_tests/README.md | 7 - rustlings/exercises/17_tests/tests1.rs | 24 --- rustlings/exercises/17_tests/tests2.rs | 23 --- rustlings/exercises/17_tests/tests3.rs | 51 ----- rustlings/exercises/18_iterators/README.md | 8 - rustlings/exercises/18_iterators/iterators1.rs | 25 --- rustlings/exercises/18_iterators/iterators2.rs | 63 ------ rustlings/exercises/18_iterators/iterators3.rs | 84 -------- rustlings/exercises/18_iterators/iterators4.rs | 42 ---- rustlings/exercises/18_iterators/iterators5.rs | 155 -------------- rustlings/exercises/19_smart_pointers/README.md | 12 -- rustlings/exercises/19_smart_pointers/arc1.rs | 45 ----- rustlings/exercises/19_smart_pointers/box1.rs | 50 ----- rustlings/exercises/19_smart_pointers/cow1.rs | 66 ------ rustlings/exercises/19_smart_pointers/rc1.rs | 108 ---------- rustlings/exercises/20_threads/README.md | 10 - rustlings/exercises/20_threads/threads1.rs | 37 ---- rustlings/exercises/20_threads/threads2.rs | 34 ---- rustlings/exercises/20_threads/threads3.rs | 60 ------ rustlings/exercises/21_macros/README.md | 15 -- rustlings/exercises/21_macros/macros1.rs | 10 - rustlings/exercises/21_macros/macros2.rs | 10 - rustlings/exercises/21_macros/macros3.rs | 13 -- rustlings/exercises/21_macros/macros4.rs | 15 -- rustlings/exercises/22_clippy/README.md | 10 - rustlings/exercises/22_clippy/clippy1.rs | 15 -- rustlings/exercises/22_clippy/clippy2.rs | 10 - rustlings/exercises/22_clippy/clippy3.rs | 29 --- rustlings/exercises/23_conversions/README.md | 23 --- rustlings/exercises/23_conversions/as_ref_mut.rs | 62 ------ rustlings/exercises/23_conversions/from_into.rs | 130 ------------ rustlings/exercises/23_conversions/from_str.rs | 113 ----------- .../exercises/23_conversions/try_from_into.rs | 177 ---------------- rustlings/exercises/23_conversions/using_as.rs | 24 --- rustlings/exercises/README.md | 27 --- rustlings/exercises/quizzes/README.md | 3 - rustlings/exercises/quizzes/quiz1.rs | 35 ---- rustlings/exercises/quizzes/quiz2.rs | 81 -------- rustlings/exercises/quizzes/quiz3.rs | 64 ------ rustlings/rust-analyzer.toml | 3 - rustlings/solutions/00_intro/intro1.rs | 5 - rustlings/solutions/00_intro/intro2.rs | 4 - rustlings/solutions/01_variables/variables1.rs | 6 - rustlings/solutions/01_variables/variables2.rs | 16 -- rustlings/solutions/01_variables/variables3.rs | 15 -- rustlings/solutions/01_variables/variables4.rs | 9 - rustlings/solutions/01_variables/variables5.rs | 9 - rustlings/solutions/01_variables/variables6.rs | 6 - rustlings/solutions/02_functions/functions1.rs | 8 - rustlings/solutions/02_functions/functions2.rs | 11 - rustlings/solutions/02_functions/functions3.rs | 10 - rustlings/solutions/02_functions/functions4.rs | 17 -- rustlings/solutions/02_functions/functions5.rs | 9 - rustlings/solutions/03_if/if1.rs | 28 --- rustlings/solutions/03_if/if2.rs | 35 ---- rustlings/solutions/03_if/if3.rs | 53 ----- .../04_primitive_types/primitive_types1.rs | 11 - .../04_primitive_types/primitive_types2.rs | 21 -- .../04_primitive_types/primitive_types3.rs | 11 - .../04_primitive_types/primitive_types4.rs | 23 --- .../04_primitive_types/primitive_types5.rs | 8 - .../04_primitive_types/primitive_types6.rs | 16 -- rustlings/solutions/05_vecs/vecs1.rs | 23 --- rustlings/solutions/05_vecs/vecs2.rs | 55 ----- .../solutions/06_move_semantics/move_semantics1.rs | 25 --- .../solutions/06_move_semantics/move_semantics2.rs | 28 --- .../solutions/06_move_semantics/move_semantics3.rs | 22 -- .../solutions/06_move_semantics/move_semantics4.rs | 19 -- .../solutions/06_move_semantics/move_semantics5.rs | 23 --- rustlings/solutions/07_structs/structs1.rs | 49 ----- rustlings/solutions/07_structs/structs2.rs | 51 ----- rustlings/solutions/07_structs/structs3.rs | 83 -------- rustlings/solutions/08_enums/enums1.rs | 16 -- rustlings/solutions/08_enums/enums2.rs | 37 ---- rustlings/solutions/08_enums/enums3.rs | 92 --------- rustlings/solutions/09_strings/strings1.rs | 9 - rustlings/solutions/09_strings/strings2.rs | 15 -- rustlings/solutions/09_strings/strings3.rs | 49 ----- rustlings/solutions/09_strings/strings4.rs | 38 ---- rustlings/solutions/10_modules/modules1.rs | 15 -- rustlings/solutions/10_modules/modules2.rs | 23 --- rustlings/solutions/10_modules/modules3.rs | 8 - rustlings/solutions/11_hashmaps/hashmaps1.rs | 42 ---- rustlings/solutions/11_hashmaps/hashmaps2.rs | 96 --------- rustlings/solutions/11_hashmaps/hashmaps3.rs | 85 -------- rustlings/solutions/12_options/options1.rs | 39 ---- rustlings/solutions/12_options/options2.rs | 37 ---- rustlings/solutions/12_options/options3.rs | 27 --- rustlings/solutions/13_error_handling/errors1.rs | 37 ---- rustlings/solutions/13_error_handling/errors2.rs | 58 ------ rustlings/solutions/13_error_handling/errors3.rs | 32 --- rustlings/solutions/13_error_handling/errors4.rs | 42 ---- rustlings/solutions/13_error_handling/errors5.rs | 54 ----- rustlings/solutions/13_error_handling/errors6.rs | 106 ---------- rustlings/solutions/14_generics/generics1.rs | 17 -- rustlings/solutions/14_generics/generics2.rs | 28 --- rustlings/solutions/15_traits/traits1.rs | 32 --- rustlings/solutions/15_traits/traits2.rs | 27 --- rustlings/solutions/15_traits/traits3.rs | 36 ---- rustlings/solutions/15_traits/traits4.rs | 35 ---- rustlings/solutions/15_traits/traits5.rs | 39 ---- rustlings/solutions/16_lifetimes/lifetimes1.rs | 24 --- rustlings/solutions/16_lifetimes/lifetimes2.rs | 29 --- rustlings/solutions/16_lifetimes/lifetimes3.rs | 18 -- rustlings/solutions/17_tests/tests1.rs | 24 --- rustlings/solutions/17_tests/tests2.rs | 22 -- rustlings/solutions/17_tests/tests3.rs | 45 ----- rustlings/solutions/18_iterators/iterators1.rs | 26 --- rustlings/solutions/18_iterators/iterators2.rs | 56 ------ rustlings/solutions/18_iterators/iterators3.rs | 88 -------- rustlings/solutions/18_iterators/iterators4.rs | 72 ------- rustlings/solutions/18_iterators/iterators5.rs | 168 ---------------- rustlings/solutions/19_smart_pointers/arc1.rs | 45 ----- rustlings/solutions/19_smart_pointers/box1.rs | 47 ----- rustlings/solutions/19_smart_pointers/cow1.rs | 69 ------- rustlings/solutions/19_smart_pointers/rc1.rs | 102 ---------- rustlings/solutions/20_threads/threads1.rs | 4 - rustlings/solutions/20_threads/threads2.rs | 4 - rustlings/solutions/20_threads/threads3.rs | 4 - rustlings/solutions/21_macros/macros1.rs | 4 - rustlings/solutions/21_macros/macros2.rs | 4 - rustlings/solutions/21_macros/macros3.rs | 4 - rustlings/solutions/21_macros/macros4.rs | 4 - rustlings/solutions/22_clippy/clippy1.rs | 4 - rustlings/solutions/22_clippy/clippy2.rs | 4 - rustlings/solutions/22_clippy/clippy3.rs | 4 - rustlings/solutions/23_conversions/as_ref_mut.rs | 4 - rustlings/solutions/23_conversions/from_into.rs | 4 - rustlings/solutions/23_conversions/from_str.rs | 4 - .../solutions/23_conversions/try_from_into.rs | 4 - rustlings/solutions/23_conversions/using_as.rs | 4 - rustlings/solutions/README.md | 6 - rustlings/solutions/quizzes/quiz1.rs | 30 --- rustlings/solutions/quizzes/quiz2.rs | 90 --------- rustlings/solutions/quizzes/quiz3.rs | 65 ------ 440 files changed, 7190 insertions(+), 7190 deletions(-) create mode 100644 rust/rustlings/.gitattributes create mode 100644 rust/rustlings/.gitignore create mode 100644 rust/rustlings/.rustlings-state.txt create mode 100644 rust/rustlings/Cargo.toml create mode 100644 rust/rustlings/exercises/00_intro/README.md create mode 100644 rust/rustlings/exercises/00_intro/intro1.rs create mode 100644 rust/rustlings/exercises/00_intro/intro2.rs create mode 100644 rust/rustlings/exercises/01_variables/README.md create mode 100644 rust/rustlings/exercises/01_variables/variables1.rs create mode 100644 rust/rustlings/exercises/01_variables/variables2.rs create mode 100644 rust/rustlings/exercises/01_variables/variables3.rs create mode 100644 rust/rustlings/exercises/01_variables/variables4.rs create mode 100644 rust/rustlings/exercises/01_variables/variables5.rs create mode 100644 rust/rustlings/exercises/01_variables/variables6.rs create mode 100644 rust/rustlings/exercises/02_functions/README.md create mode 100644 rust/rustlings/exercises/02_functions/functions1.rs create mode 100644 rust/rustlings/exercises/02_functions/functions2.rs create mode 100644 rust/rustlings/exercises/02_functions/functions3.rs create mode 100644 rust/rustlings/exercises/02_functions/functions4.rs create mode 100644 rust/rustlings/exercises/02_functions/functions5.rs create mode 100644 rust/rustlings/exercises/03_if/README.md create mode 100644 rust/rustlings/exercises/03_if/if1.rs create mode 100644 rust/rustlings/exercises/03_if/if2.rs create mode 100644 rust/rustlings/exercises/03_if/if3.rs create mode 100644 rust/rustlings/exercises/04_primitive_types/README.md create mode 100644 rust/rustlings/exercises/04_primitive_types/primitive_types1.rs create mode 100644 rust/rustlings/exercises/04_primitive_types/primitive_types2.rs create mode 100644 rust/rustlings/exercises/04_primitive_types/primitive_types3.rs create mode 100644 rust/rustlings/exercises/04_primitive_types/primitive_types4.rs create mode 100644 rust/rustlings/exercises/04_primitive_types/primitive_types5.rs create mode 100644 rust/rustlings/exercises/04_primitive_types/primitive_types6.rs create mode 100644 rust/rustlings/exercises/05_vecs/README.md create mode 100644 rust/rustlings/exercises/05_vecs/vecs1.rs create mode 100644 rust/rustlings/exercises/05_vecs/vecs2.rs create mode 100644 rust/rustlings/exercises/06_move_semantics/README.md create mode 100644 rust/rustlings/exercises/06_move_semantics/move_semantics1.rs create mode 100644 rust/rustlings/exercises/06_move_semantics/move_semantics2.rs create mode 100644 rust/rustlings/exercises/06_move_semantics/move_semantics3.rs create mode 100644 rust/rustlings/exercises/06_move_semantics/move_semantics4.rs create mode 100644 rust/rustlings/exercises/06_move_semantics/move_semantics5.rs create mode 100644 rust/rustlings/exercises/07_structs/README.md create mode 100644 rust/rustlings/exercises/07_structs/structs1.rs create mode 100644 rust/rustlings/exercises/07_structs/structs2.rs create mode 100644 rust/rustlings/exercises/07_structs/structs3.rs create mode 100644 rust/rustlings/exercises/08_enums/README.md create mode 100644 rust/rustlings/exercises/08_enums/enums1.rs create mode 100644 rust/rustlings/exercises/08_enums/enums2.rs create mode 100644 rust/rustlings/exercises/08_enums/enums3.rs create mode 100644 rust/rustlings/exercises/09_strings/README.md create mode 100644 rust/rustlings/exercises/09_strings/strings1.rs create mode 100644 rust/rustlings/exercises/09_strings/strings2.rs create mode 100644 rust/rustlings/exercises/09_strings/strings3.rs create mode 100644 rust/rustlings/exercises/09_strings/strings4.rs create mode 100644 rust/rustlings/exercises/10_modules/README.md create mode 100644 rust/rustlings/exercises/10_modules/modules1.rs create mode 100644 rust/rustlings/exercises/10_modules/modules2.rs create mode 100644 rust/rustlings/exercises/10_modules/modules3.rs create mode 100644 rust/rustlings/exercises/11_hashmaps/README.md create mode 100644 rust/rustlings/exercises/11_hashmaps/hashmaps1.rs create mode 100644 rust/rustlings/exercises/11_hashmaps/hashmaps2.rs create mode 100644 rust/rustlings/exercises/11_hashmaps/hashmaps3.rs create mode 100644 rust/rustlings/exercises/12_options/README.md create mode 100644 rust/rustlings/exercises/12_options/options1.rs create mode 100644 rust/rustlings/exercises/12_options/options2.rs create mode 100644 rust/rustlings/exercises/12_options/options3.rs create mode 100644 rust/rustlings/exercises/13_error_handling/README.md create mode 100644 rust/rustlings/exercises/13_error_handling/errors1.rs create mode 100644 rust/rustlings/exercises/13_error_handling/errors2.rs create mode 100644 rust/rustlings/exercises/13_error_handling/errors3.rs create mode 100644 rust/rustlings/exercises/13_error_handling/errors4.rs create mode 100644 rust/rustlings/exercises/13_error_handling/errors5.rs create mode 100644 rust/rustlings/exercises/13_error_handling/errors6.rs create mode 100644 rust/rustlings/exercises/14_generics/README.md create mode 100644 rust/rustlings/exercises/14_generics/generics1.rs create mode 100644 rust/rustlings/exercises/14_generics/generics2.rs create mode 100644 rust/rustlings/exercises/15_traits/README.md create mode 100644 rust/rustlings/exercises/15_traits/traits1.rs create mode 100644 rust/rustlings/exercises/15_traits/traits2.rs create mode 100644 rust/rustlings/exercises/15_traits/traits3.rs create mode 100644 rust/rustlings/exercises/15_traits/traits4.rs create mode 100644 rust/rustlings/exercises/15_traits/traits5.rs create mode 100644 rust/rustlings/exercises/16_lifetimes/README.md create mode 100644 rust/rustlings/exercises/16_lifetimes/lifetimes1.rs create mode 100644 rust/rustlings/exercises/16_lifetimes/lifetimes2.rs create mode 100644 rust/rustlings/exercises/16_lifetimes/lifetimes3.rs create mode 100644 rust/rustlings/exercises/17_tests/README.md create mode 100644 rust/rustlings/exercises/17_tests/tests1.rs create mode 100644 rust/rustlings/exercises/17_tests/tests2.rs create mode 100644 rust/rustlings/exercises/17_tests/tests3.rs create mode 100644 rust/rustlings/exercises/18_iterators/README.md create mode 100644 rust/rustlings/exercises/18_iterators/iterators1.rs create mode 100644 rust/rustlings/exercises/18_iterators/iterators2.rs create mode 100644 rust/rustlings/exercises/18_iterators/iterators3.rs create mode 100644 rust/rustlings/exercises/18_iterators/iterators4.rs create mode 100644 rust/rustlings/exercises/18_iterators/iterators5.rs create mode 100644 rust/rustlings/exercises/19_smart_pointers/README.md create mode 100644 rust/rustlings/exercises/19_smart_pointers/arc1.rs create mode 100644 rust/rustlings/exercises/19_smart_pointers/box1.rs create mode 100644 rust/rustlings/exercises/19_smart_pointers/cow1.rs create mode 100644 rust/rustlings/exercises/19_smart_pointers/rc1.rs create mode 100644 rust/rustlings/exercises/20_threads/README.md create mode 100644 rust/rustlings/exercises/20_threads/threads1.rs create mode 100644 rust/rustlings/exercises/20_threads/threads2.rs create mode 100644 rust/rustlings/exercises/20_threads/threads3.rs create mode 100644 rust/rustlings/exercises/21_macros/README.md create mode 100644 rust/rustlings/exercises/21_macros/macros1.rs create mode 100644 rust/rustlings/exercises/21_macros/macros2.rs create mode 100644 rust/rustlings/exercises/21_macros/macros3.rs create mode 100644 rust/rustlings/exercises/21_macros/macros4.rs create mode 100644 rust/rustlings/exercises/22_clippy/README.md create mode 100644 rust/rustlings/exercises/22_clippy/clippy1.rs create mode 100644 rust/rustlings/exercises/22_clippy/clippy2.rs create mode 100644 rust/rustlings/exercises/22_clippy/clippy3.rs create mode 100644 rust/rustlings/exercises/23_conversions/README.md create mode 100644 rust/rustlings/exercises/23_conversions/as_ref_mut.rs create mode 100644 rust/rustlings/exercises/23_conversions/from_into.rs create mode 100644 rust/rustlings/exercises/23_conversions/from_str.rs create mode 100644 rust/rustlings/exercises/23_conversions/try_from_into.rs create mode 100644 rust/rustlings/exercises/23_conversions/using_as.rs create mode 100644 rust/rustlings/exercises/README.md create mode 100644 rust/rustlings/exercises/quizzes/README.md create mode 100644 rust/rustlings/exercises/quizzes/quiz1.rs create mode 100644 rust/rustlings/exercises/quizzes/quiz2.rs create mode 100644 rust/rustlings/exercises/quizzes/quiz3.rs create mode 100644 rust/rustlings/rust-analyzer.toml create mode 100644 rust/rustlings/solutions/00_intro/intro1.rs create mode 100644 rust/rustlings/solutions/00_intro/intro2.rs create mode 100644 rust/rustlings/solutions/01_variables/variables1.rs create mode 100644 rust/rustlings/solutions/01_variables/variables2.rs create mode 100644 rust/rustlings/solutions/01_variables/variables3.rs create mode 100644 rust/rustlings/solutions/01_variables/variables4.rs create mode 100644 rust/rustlings/solutions/01_variables/variables5.rs create mode 100644 rust/rustlings/solutions/01_variables/variables6.rs create mode 100644 rust/rustlings/solutions/02_functions/functions1.rs create mode 100644 rust/rustlings/solutions/02_functions/functions2.rs create mode 100644 rust/rustlings/solutions/02_functions/functions3.rs create mode 100644 rust/rustlings/solutions/02_functions/functions4.rs create mode 100644 rust/rustlings/solutions/02_functions/functions5.rs create mode 100644 rust/rustlings/solutions/03_if/if1.rs create mode 100644 rust/rustlings/solutions/03_if/if2.rs create mode 100644 rust/rustlings/solutions/03_if/if3.rs create mode 100644 rust/rustlings/solutions/04_primitive_types/primitive_types1.rs create mode 100644 rust/rustlings/solutions/04_primitive_types/primitive_types2.rs create mode 100644 rust/rustlings/solutions/04_primitive_types/primitive_types3.rs create mode 100644 rust/rustlings/solutions/04_primitive_types/primitive_types4.rs create mode 100644 rust/rustlings/solutions/04_primitive_types/primitive_types5.rs create mode 100644 rust/rustlings/solutions/04_primitive_types/primitive_types6.rs create mode 100644 rust/rustlings/solutions/05_vecs/vecs1.rs create mode 100644 rust/rustlings/solutions/05_vecs/vecs2.rs create mode 100644 rust/rustlings/solutions/06_move_semantics/move_semantics1.rs create mode 100644 rust/rustlings/solutions/06_move_semantics/move_semantics2.rs create mode 100644 rust/rustlings/solutions/06_move_semantics/move_semantics3.rs create mode 100644 rust/rustlings/solutions/06_move_semantics/move_semantics4.rs create mode 100644 rust/rustlings/solutions/06_move_semantics/move_semantics5.rs create mode 100644 rust/rustlings/solutions/07_structs/structs1.rs create mode 100644 rust/rustlings/solutions/07_structs/structs2.rs create mode 100644 rust/rustlings/solutions/07_structs/structs3.rs create mode 100644 rust/rustlings/solutions/08_enums/enums1.rs create mode 100644 rust/rustlings/solutions/08_enums/enums2.rs create mode 100644 rust/rustlings/solutions/08_enums/enums3.rs create mode 100644 rust/rustlings/solutions/09_strings/strings1.rs create mode 100644 rust/rustlings/solutions/09_strings/strings2.rs create mode 100644 rust/rustlings/solutions/09_strings/strings3.rs create mode 100644 rust/rustlings/solutions/09_strings/strings4.rs create mode 100644 rust/rustlings/solutions/10_modules/modules1.rs create mode 100644 rust/rustlings/solutions/10_modules/modules2.rs create mode 100644 rust/rustlings/solutions/10_modules/modules3.rs create mode 100644 rust/rustlings/solutions/11_hashmaps/hashmaps1.rs create mode 100644 rust/rustlings/solutions/11_hashmaps/hashmaps2.rs create mode 100644 rust/rustlings/solutions/11_hashmaps/hashmaps3.rs create mode 100644 rust/rustlings/solutions/12_options/options1.rs create mode 100644 rust/rustlings/solutions/12_options/options2.rs create mode 100644 rust/rustlings/solutions/12_options/options3.rs create mode 100644 rust/rustlings/solutions/13_error_handling/errors1.rs create mode 100644 rust/rustlings/solutions/13_error_handling/errors2.rs create mode 100644 rust/rustlings/solutions/13_error_handling/errors3.rs create mode 100644 rust/rustlings/solutions/13_error_handling/errors4.rs create mode 100644 rust/rustlings/solutions/13_error_handling/errors5.rs create mode 100644 rust/rustlings/solutions/13_error_handling/errors6.rs create mode 100644 rust/rustlings/solutions/14_generics/generics1.rs create mode 100644 rust/rustlings/solutions/14_generics/generics2.rs create mode 100644 rust/rustlings/solutions/15_traits/traits1.rs create mode 100644 rust/rustlings/solutions/15_traits/traits2.rs create mode 100644 rust/rustlings/solutions/15_traits/traits3.rs create mode 100644 rust/rustlings/solutions/15_traits/traits4.rs create mode 100644 rust/rustlings/solutions/15_traits/traits5.rs create mode 100644 rust/rustlings/solutions/16_lifetimes/lifetimes1.rs create mode 100644 rust/rustlings/solutions/16_lifetimes/lifetimes2.rs create mode 100644 rust/rustlings/solutions/16_lifetimes/lifetimes3.rs create mode 100644 rust/rustlings/solutions/17_tests/tests1.rs create mode 100644 rust/rustlings/solutions/17_tests/tests2.rs create mode 100644 rust/rustlings/solutions/17_tests/tests3.rs create mode 100644 rust/rustlings/solutions/18_iterators/iterators1.rs create mode 100644 rust/rustlings/solutions/18_iterators/iterators2.rs create mode 100644 rust/rustlings/solutions/18_iterators/iterators3.rs create mode 100644 rust/rustlings/solutions/18_iterators/iterators4.rs create mode 100644 rust/rustlings/solutions/18_iterators/iterators5.rs create mode 100644 rust/rustlings/solutions/19_smart_pointers/arc1.rs create mode 100644 rust/rustlings/solutions/19_smart_pointers/box1.rs create mode 100644 rust/rustlings/solutions/19_smart_pointers/cow1.rs create mode 100644 rust/rustlings/solutions/19_smart_pointers/rc1.rs create mode 100644 rust/rustlings/solutions/20_threads/threads1.rs create mode 100644 rust/rustlings/solutions/20_threads/threads2.rs create mode 100644 rust/rustlings/solutions/20_threads/threads3.rs create mode 100644 rust/rustlings/solutions/21_macros/macros1.rs create mode 100644 rust/rustlings/solutions/21_macros/macros2.rs create mode 100644 rust/rustlings/solutions/21_macros/macros3.rs create mode 100644 rust/rustlings/solutions/21_macros/macros4.rs create mode 100644 rust/rustlings/solutions/22_clippy/clippy1.rs create mode 100644 rust/rustlings/solutions/22_clippy/clippy2.rs create mode 100644 rust/rustlings/solutions/22_clippy/clippy3.rs create mode 100644 rust/rustlings/solutions/23_conversions/as_ref_mut.rs create mode 100644 rust/rustlings/solutions/23_conversions/from_into.rs create mode 100644 rust/rustlings/solutions/23_conversions/from_str.rs create mode 100644 rust/rustlings/solutions/23_conversions/try_from_into.rs create mode 100644 rust/rustlings/solutions/23_conversions/using_as.rs create mode 100644 rust/rustlings/solutions/README.md create mode 100644 rust/rustlings/solutions/quizzes/quiz1.rs create mode 100644 rust/rustlings/solutions/quizzes/quiz2.rs create mode 100644 rust/rustlings/solutions/quizzes/quiz3.rs delete mode 100644 rustlings/.gitattributes delete mode 100644 rustlings/.gitignore delete mode 100644 rustlings/.rustlings-state.txt delete mode 100644 rustlings/Cargo.toml delete mode 100644 rustlings/exercises/00_intro/README.md delete mode 100644 rustlings/exercises/00_intro/intro1.rs delete mode 100644 rustlings/exercises/00_intro/intro2.rs delete mode 100644 rustlings/exercises/01_variables/README.md delete mode 100644 rustlings/exercises/01_variables/variables1.rs delete mode 100644 rustlings/exercises/01_variables/variables2.rs delete mode 100644 rustlings/exercises/01_variables/variables3.rs delete mode 100644 rustlings/exercises/01_variables/variables4.rs delete mode 100644 rustlings/exercises/01_variables/variables5.rs delete mode 100644 rustlings/exercises/01_variables/variables6.rs delete mode 100644 rustlings/exercises/02_functions/README.md delete mode 100644 rustlings/exercises/02_functions/functions1.rs delete mode 100644 rustlings/exercises/02_functions/functions2.rs delete mode 100644 rustlings/exercises/02_functions/functions3.rs delete mode 100644 rustlings/exercises/02_functions/functions4.rs delete mode 100644 rustlings/exercises/02_functions/functions5.rs delete mode 100644 rustlings/exercises/03_if/README.md delete mode 100644 rustlings/exercises/03_if/if1.rs delete mode 100644 rustlings/exercises/03_if/if2.rs delete mode 100644 rustlings/exercises/03_if/if3.rs delete mode 100644 rustlings/exercises/04_primitive_types/README.md delete mode 100644 rustlings/exercises/04_primitive_types/primitive_types1.rs delete mode 100644 rustlings/exercises/04_primitive_types/primitive_types2.rs delete mode 100644 rustlings/exercises/04_primitive_types/primitive_types3.rs delete mode 100644 rustlings/exercises/04_primitive_types/primitive_types4.rs delete mode 100644 rustlings/exercises/04_primitive_types/primitive_types5.rs delete mode 100644 rustlings/exercises/04_primitive_types/primitive_types6.rs delete mode 100644 rustlings/exercises/05_vecs/README.md delete mode 100644 rustlings/exercises/05_vecs/vecs1.rs delete mode 100644 rustlings/exercises/05_vecs/vecs2.rs delete mode 100644 rustlings/exercises/06_move_semantics/README.md delete mode 100644 rustlings/exercises/06_move_semantics/move_semantics1.rs delete mode 100644 rustlings/exercises/06_move_semantics/move_semantics2.rs delete mode 100644 rustlings/exercises/06_move_semantics/move_semantics3.rs delete mode 100644 rustlings/exercises/06_move_semantics/move_semantics4.rs delete mode 100644 rustlings/exercises/06_move_semantics/move_semantics5.rs delete mode 100644 rustlings/exercises/07_structs/README.md delete mode 100644 rustlings/exercises/07_structs/structs1.rs delete mode 100644 rustlings/exercises/07_structs/structs2.rs delete mode 100644 rustlings/exercises/07_structs/structs3.rs delete mode 100644 rustlings/exercises/08_enums/README.md delete mode 100644 rustlings/exercises/08_enums/enums1.rs delete mode 100644 rustlings/exercises/08_enums/enums2.rs delete mode 100644 rustlings/exercises/08_enums/enums3.rs delete mode 100644 rustlings/exercises/09_strings/README.md delete mode 100644 rustlings/exercises/09_strings/strings1.rs delete mode 100644 rustlings/exercises/09_strings/strings2.rs delete mode 100644 rustlings/exercises/09_strings/strings3.rs delete mode 100644 rustlings/exercises/09_strings/strings4.rs delete mode 100644 rustlings/exercises/10_modules/README.md delete mode 100644 rustlings/exercises/10_modules/modules1.rs delete mode 100644 rustlings/exercises/10_modules/modules2.rs delete mode 100644 rustlings/exercises/10_modules/modules3.rs delete mode 100644 rustlings/exercises/11_hashmaps/README.md delete mode 100644 rustlings/exercises/11_hashmaps/hashmaps1.rs delete mode 100644 rustlings/exercises/11_hashmaps/hashmaps2.rs delete mode 100644 rustlings/exercises/11_hashmaps/hashmaps3.rs delete mode 100644 rustlings/exercises/12_options/README.md delete mode 100644 rustlings/exercises/12_options/options1.rs delete mode 100644 rustlings/exercises/12_options/options2.rs delete mode 100644 rustlings/exercises/12_options/options3.rs delete mode 100644 rustlings/exercises/13_error_handling/README.md delete mode 100644 rustlings/exercises/13_error_handling/errors1.rs delete mode 100644 rustlings/exercises/13_error_handling/errors2.rs delete mode 100644 rustlings/exercises/13_error_handling/errors3.rs delete mode 100644 rustlings/exercises/13_error_handling/errors4.rs delete mode 100644 rustlings/exercises/13_error_handling/errors5.rs delete mode 100644 rustlings/exercises/13_error_handling/errors6.rs delete mode 100644 rustlings/exercises/14_generics/README.md delete mode 100644 rustlings/exercises/14_generics/generics1.rs delete mode 100644 rustlings/exercises/14_generics/generics2.rs delete mode 100644 rustlings/exercises/15_traits/README.md delete mode 100644 rustlings/exercises/15_traits/traits1.rs delete mode 100644 rustlings/exercises/15_traits/traits2.rs delete mode 100644 rustlings/exercises/15_traits/traits3.rs delete mode 100644 rustlings/exercises/15_traits/traits4.rs delete mode 100644 rustlings/exercises/15_traits/traits5.rs delete mode 100644 rustlings/exercises/16_lifetimes/README.md delete mode 100644 rustlings/exercises/16_lifetimes/lifetimes1.rs delete mode 100644 rustlings/exercises/16_lifetimes/lifetimes2.rs delete mode 100644 rustlings/exercises/16_lifetimes/lifetimes3.rs delete mode 100644 rustlings/exercises/17_tests/README.md delete mode 100644 rustlings/exercises/17_tests/tests1.rs delete mode 100644 rustlings/exercises/17_tests/tests2.rs delete mode 100644 rustlings/exercises/17_tests/tests3.rs delete mode 100644 rustlings/exercises/18_iterators/README.md delete mode 100644 rustlings/exercises/18_iterators/iterators1.rs delete mode 100644 rustlings/exercises/18_iterators/iterators2.rs delete mode 100644 rustlings/exercises/18_iterators/iterators3.rs delete mode 100644 rustlings/exercises/18_iterators/iterators4.rs delete mode 100644 rustlings/exercises/18_iterators/iterators5.rs delete mode 100644 rustlings/exercises/19_smart_pointers/README.md delete mode 100644 rustlings/exercises/19_smart_pointers/arc1.rs delete mode 100644 rustlings/exercises/19_smart_pointers/box1.rs delete mode 100644 rustlings/exercises/19_smart_pointers/cow1.rs delete mode 100644 rustlings/exercises/19_smart_pointers/rc1.rs delete mode 100644 rustlings/exercises/20_threads/README.md delete mode 100644 rustlings/exercises/20_threads/threads1.rs delete mode 100644 rustlings/exercises/20_threads/threads2.rs delete mode 100644 rustlings/exercises/20_threads/threads3.rs delete mode 100644 rustlings/exercises/21_macros/README.md delete mode 100644 rustlings/exercises/21_macros/macros1.rs delete mode 100644 rustlings/exercises/21_macros/macros2.rs delete mode 100644 rustlings/exercises/21_macros/macros3.rs delete mode 100644 rustlings/exercises/21_macros/macros4.rs delete mode 100644 rustlings/exercises/22_clippy/README.md delete mode 100644 rustlings/exercises/22_clippy/clippy1.rs delete mode 100644 rustlings/exercises/22_clippy/clippy2.rs delete mode 100644 rustlings/exercises/22_clippy/clippy3.rs delete mode 100644 rustlings/exercises/23_conversions/README.md delete mode 100644 rustlings/exercises/23_conversions/as_ref_mut.rs delete mode 100644 rustlings/exercises/23_conversions/from_into.rs delete mode 100644 rustlings/exercises/23_conversions/from_str.rs delete mode 100644 rustlings/exercises/23_conversions/try_from_into.rs delete mode 100644 rustlings/exercises/23_conversions/using_as.rs delete mode 100644 rustlings/exercises/README.md delete mode 100644 rustlings/exercises/quizzes/README.md delete mode 100644 rustlings/exercises/quizzes/quiz1.rs delete mode 100644 rustlings/exercises/quizzes/quiz2.rs delete mode 100644 rustlings/exercises/quizzes/quiz3.rs delete mode 100644 rustlings/rust-analyzer.toml delete mode 100644 rustlings/solutions/00_intro/intro1.rs delete mode 100644 rustlings/solutions/00_intro/intro2.rs delete mode 100644 rustlings/solutions/01_variables/variables1.rs delete mode 100644 rustlings/solutions/01_variables/variables2.rs delete mode 100644 rustlings/solutions/01_variables/variables3.rs delete mode 100644 rustlings/solutions/01_variables/variables4.rs delete mode 100644 rustlings/solutions/01_variables/variables5.rs delete mode 100644 rustlings/solutions/01_variables/variables6.rs delete mode 100644 rustlings/solutions/02_functions/functions1.rs delete mode 100644 rustlings/solutions/02_functions/functions2.rs delete mode 100644 rustlings/solutions/02_functions/functions3.rs delete mode 100644 rustlings/solutions/02_functions/functions4.rs delete mode 100644 rustlings/solutions/02_functions/functions5.rs delete mode 100644 rustlings/solutions/03_if/if1.rs delete mode 100644 rustlings/solutions/03_if/if2.rs delete mode 100644 rustlings/solutions/03_if/if3.rs delete mode 100644 rustlings/solutions/04_primitive_types/primitive_types1.rs delete mode 100644 rustlings/solutions/04_primitive_types/primitive_types2.rs delete mode 100644 rustlings/solutions/04_primitive_types/primitive_types3.rs delete mode 100644 rustlings/solutions/04_primitive_types/primitive_types4.rs delete mode 100644 rustlings/solutions/04_primitive_types/primitive_types5.rs delete mode 100644 rustlings/solutions/04_primitive_types/primitive_types6.rs delete mode 100644 rustlings/solutions/05_vecs/vecs1.rs delete mode 100644 rustlings/solutions/05_vecs/vecs2.rs delete mode 100644 rustlings/solutions/06_move_semantics/move_semantics1.rs delete mode 100644 rustlings/solutions/06_move_semantics/move_semantics2.rs delete mode 100644 rustlings/solutions/06_move_semantics/move_semantics3.rs delete mode 100644 rustlings/solutions/06_move_semantics/move_semantics4.rs delete mode 100644 rustlings/solutions/06_move_semantics/move_semantics5.rs delete mode 100644 rustlings/solutions/07_structs/structs1.rs delete mode 100644 rustlings/solutions/07_structs/structs2.rs delete mode 100644 rustlings/solutions/07_structs/structs3.rs delete mode 100644 rustlings/solutions/08_enums/enums1.rs delete mode 100644 rustlings/solutions/08_enums/enums2.rs delete mode 100644 rustlings/solutions/08_enums/enums3.rs delete mode 100644 rustlings/solutions/09_strings/strings1.rs delete mode 100644 rustlings/solutions/09_strings/strings2.rs delete mode 100644 rustlings/solutions/09_strings/strings3.rs delete mode 100644 rustlings/solutions/09_strings/strings4.rs delete mode 100644 rustlings/solutions/10_modules/modules1.rs delete mode 100644 rustlings/solutions/10_modules/modules2.rs delete mode 100644 rustlings/solutions/10_modules/modules3.rs delete mode 100644 rustlings/solutions/11_hashmaps/hashmaps1.rs delete mode 100644 rustlings/solutions/11_hashmaps/hashmaps2.rs delete mode 100644 rustlings/solutions/11_hashmaps/hashmaps3.rs delete mode 100644 rustlings/solutions/12_options/options1.rs delete mode 100644 rustlings/solutions/12_options/options2.rs delete mode 100644 rustlings/solutions/12_options/options3.rs delete mode 100644 rustlings/solutions/13_error_handling/errors1.rs delete mode 100644 rustlings/solutions/13_error_handling/errors2.rs delete mode 100644 rustlings/solutions/13_error_handling/errors3.rs delete mode 100644 rustlings/solutions/13_error_handling/errors4.rs delete mode 100644 rustlings/solutions/13_error_handling/errors5.rs delete mode 100644 rustlings/solutions/13_error_handling/errors6.rs delete mode 100644 rustlings/solutions/14_generics/generics1.rs delete mode 100644 rustlings/solutions/14_generics/generics2.rs delete mode 100644 rustlings/solutions/15_traits/traits1.rs delete mode 100644 rustlings/solutions/15_traits/traits2.rs delete mode 100644 rustlings/solutions/15_traits/traits3.rs delete mode 100644 rustlings/solutions/15_traits/traits4.rs delete mode 100644 rustlings/solutions/15_traits/traits5.rs delete mode 100644 rustlings/solutions/16_lifetimes/lifetimes1.rs delete mode 100644 rustlings/solutions/16_lifetimes/lifetimes2.rs delete mode 100644 rustlings/solutions/16_lifetimes/lifetimes3.rs delete mode 100644 rustlings/solutions/17_tests/tests1.rs delete mode 100644 rustlings/solutions/17_tests/tests2.rs delete mode 100644 rustlings/solutions/17_tests/tests3.rs delete mode 100644 rustlings/solutions/18_iterators/iterators1.rs delete mode 100644 rustlings/solutions/18_iterators/iterators2.rs delete mode 100644 rustlings/solutions/18_iterators/iterators3.rs delete mode 100644 rustlings/solutions/18_iterators/iterators4.rs delete mode 100644 rustlings/solutions/18_iterators/iterators5.rs delete mode 100644 rustlings/solutions/19_smart_pointers/arc1.rs delete mode 100644 rustlings/solutions/19_smart_pointers/box1.rs delete mode 100644 rustlings/solutions/19_smart_pointers/cow1.rs delete mode 100644 rustlings/solutions/19_smart_pointers/rc1.rs delete mode 100644 rustlings/solutions/20_threads/threads1.rs delete mode 100644 rustlings/solutions/20_threads/threads2.rs delete mode 100644 rustlings/solutions/20_threads/threads3.rs delete mode 100644 rustlings/solutions/21_macros/macros1.rs delete mode 100644 rustlings/solutions/21_macros/macros2.rs delete mode 100644 rustlings/solutions/21_macros/macros3.rs delete mode 100644 rustlings/solutions/21_macros/macros4.rs delete mode 100644 rustlings/solutions/22_clippy/clippy1.rs delete mode 100644 rustlings/solutions/22_clippy/clippy2.rs delete mode 100644 rustlings/solutions/22_clippy/clippy3.rs delete mode 100644 rustlings/solutions/23_conversions/as_ref_mut.rs delete mode 100644 rustlings/solutions/23_conversions/from_into.rs delete mode 100644 rustlings/solutions/23_conversions/from_str.rs delete mode 100644 rustlings/solutions/23_conversions/try_from_into.rs delete mode 100644 rustlings/solutions/23_conversions/using_as.rs delete mode 100644 rustlings/solutions/README.md delete mode 100644 rustlings/solutions/quizzes/quiz1.rs delete mode 100644 rustlings/solutions/quizzes/quiz2.rs delete mode 100644 rustlings/solutions/quizzes/quiz3.rs diff --git a/rust/rustlings/.gitattributes b/rust/rustlings/.gitattributes new file mode 100644 index 0000000..52362b3 --- /dev/null +++ b/rust/rustlings/.gitattributes @@ -0,0 +1,2 @@ +exercises/** linguist-vendored +solutions/** linguist-vendored diff --git a/rust/rustlings/.gitignore b/rust/rustlings/.gitignore new file mode 100644 index 0000000..9182e2f --- /dev/null +++ b/rust/rustlings/.gitignore @@ -0,0 +1,3 @@ +Cargo.lock +target/ +.vscode/ diff --git a/rust/rustlings/.rustlings-state.txt b/rust/rustlings/.rustlings-state.txt new file mode 100644 index 0000000..7523b62 --- /dev/null +++ b/rust/rustlings/.rustlings-state.txt @@ -0,0 +1,83 @@ +DON'T EDIT THIS FILE! + +threads1 + +intro1 +intro2 +variables1 +variables2 +variables3 +variables4 +variables5 +variables6 +functions1 +functions2 +functions3 +functions4 +functions5 +if1 +if2 +if3 +quiz1 +primitive_types1 +primitive_types2 +primitive_types3 +primitive_types4 +primitive_types5 +primitive_types6 +vecs1 +vecs2 +move_semantics1 +move_semantics2 +move_semantics3 +move_semantics4 +move_semantics5 +structs1 +structs2 +structs3 +enums1 +enums2 +enums3 +strings1 +strings2 +strings3 +strings4 +modules1 +modules2 +modules3 +hashmaps1 +hashmaps2 +hashmaps3 +quiz2 +options1 +options2 +options3 +errors1 +errors2 +errors3 +errors4 +errors5 +errors6 +generics1 +generics2 +traits1 +traits2 +traits3 +traits4 +traits5 +quiz3 +lifetimes1 +lifetimes2 +lifetimes3 +tests1 +tests2 +tests3 +iterators1 +iterators2 +iterators3 +iterators4 +iterators5 +box1 +rc1 +arc1 +cow1 \ No newline at end of file diff --git a/rust/rustlings/Cargo.toml b/rust/rustlings/Cargo.toml new file mode 100644 index 0000000..5275c9e --- /dev/null +++ b/rust/rustlings/Cargo.toml @@ -0,0 +1,222 @@ +bin = [ + { name = "intro1", path = "exercises/00_intro/intro1.rs" }, + { name = "intro1_sol", path = "solutions/00_intro/intro1.rs" }, + { name = "intro2", path = "exercises/00_intro/intro2.rs" }, + { name = "intro2_sol", path = "solutions/00_intro/intro2.rs" }, + { name = "variables1", path = "exercises/01_variables/variables1.rs" }, + { name = "variables1_sol", path = "solutions/01_variables/variables1.rs" }, + { name = "variables2", path = "exercises/01_variables/variables2.rs" }, + { name = "variables2_sol", path = "solutions/01_variables/variables2.rs" }, + { name = "variables3", path = "exercises/01_variables/variables3.rs" }, + { name = "variables3_sol", path = "solutions/01_variables/variables3.rs" }, + { name = "variables4", path = "exercises/01_variables/variables4.rs" }, + { name = "variables4_sol", path = "solutions/01_variables/variables4.rs" }, + { name = "variables5", path = "exercises/01_variables/variables5.rs" }, + { name = "variables5_sol", path = "solutions/01_variables/variables5.rs" }, + { name = "variables6", path = "exercises/01_variables/variables6.rs" }, + { name = "variables6_sol", path = "solutions/01_variables/variables6.rs" }, + { name = "functions1", path = "exercises/02_functions/functions1.rs" }, + { name = "functions1_sol", path = "solutions/02_functions/functions1.rs" }, + { name = "functions2", path = "exercises/02_functions/functions2.rs" }, + { name = "functions2_sol", path = "solutions/02_functions/functions2.rs" }, + { name = "functions3", path = "exercises/02_functions/functions3.rs" }, + { name = "functions3_sol", path = "solutions/02_functions/functions3.rs" }, + { name = "functions4", path = "exercises/02_functions/functions4.rs" }, + { name = "functions4_sol", path = "solutions/02_functions/functions4.rs" }, + { name = "functions5", path = "exercises/02_functions/functions5.rs" }, + { name = "functions5_sol", path = "solutions/02_functions/functions5.rs" }, + { name = "if1", path = "exercises/03_if/if1.rs" }, + { name = "if1_sol", path = "solutions/03_if/if1.rs" }, + { name = "if2", path = "exercises/03_if/if2.rs" }, + { name = "if2_sol", path = "solutions/03_if/if2.rs" }, + { name = "if3", path = "exercises/03_if/if3.rs" }, + { name = "if3_sol", path = "solutions/03_if/if3.rs" }, + { name = "quiz1", path = "exercises/quizzes/quiz1.rs" }, + { name = "quiz1_sol", path = "solutions/quizzes/quiz1.rs" }, + { name = "primitive_types1", path = "exercises/04_primitive_types/primitive_types1.rs" }, + { name = "primitive_types1_sol", path = "solutions/04_primitive_types/primitive_types1.rs" }, + { name = "primitive_types2", path = "exercises/04_primitive_types/primitive_types2.rs" }, + { name = "primitive_types2_sol", path = "solutions/04_primitive_types/primitive_types2.rs" }, + { name = "primitive_types3", path = "exercises/04_primitive_types/primitive_types3.rs" }, + { name = "primitive_types3_sol", path = "solutions/04_primitive_types/primitive_types3.rs" }, + { name = "primitive_types4", path = "exercises/04_primitive_types/primitive_types4.rs" }, + { name = "primitive_types4_sol", path = "solutions/04_primitive_types/primitive_types4.rs" }, + { name = "primitive_types5", path = "exercises/04_primitive_types/primitive_types5.rs" }, + { name = "primitive_types5_sol", path = "solutions/04_primitive_types/primitive_types5.rs" }, + { name = "primitive_types6", path = "exercises/04_primitive_types/primitive_types6.rs" }, + { name = "primitive_types6_sol", path = "solutions/04_primitive_types/primitive_types6.rs" }, + { name = "vecs1", path = "exercises/05_vecs/vecs1.rs" }, + { name = "vecs1_sol", path = "solutions/05_vecs/vecs1.rs" }, + { name = "vecs2", path = "exercises/05_vecs/vecs2.rs" }, + { name = "vecs2_sol", path = "solutions/05_vecs/vecs2.rs" }, + { name = "move_semantics1", path = "exercises/06_move_semantics/move_semantics1.rs" }, + { name = "move_semantics1_sol", path = "solutions/06_move_semantics/move_semantics1.rs" }, + { name = "move_semantics2", path = "exercises/06_move_semantics/move_semantics2.rs" }, + { name = "move_semantics2_sol", path = "solutions/06_move_semantics/move_semantics2.rs" }, + { name = "move_semantics3", path = "exercises/06_move_semantics/move_semantics3.rs" }, + { name = "move_semantics3_sol", path = "solutions/06_move_semantics/move_semantics3.rs" }, + { name = "move_semantics4", path = "exercises/06_move_semantics/move_semantics4.rs" }, + { name = "move_semantics4_sol", path = "solutions/06_move_semantics/move_semantics4.rs" }, + { name = "move_semantics5", path = "exercises/06_move_semantics/move_semantics5.rs" }, + { name = "move_semantics5_sol", path = "solutions/06_move_semantics/move_semantics5.rs" }, + { name = "structs1", path = "exercises/07_structs/structs1.rs" }, + { name = "structs1_sol", path = "solutions/07_structs/structs1.rs" }, + { name = "structs2", path = "exercises/07_structs/structs2.rs" }, + { name = "structs2_sol", path = "solutions/07_structs/structs2.rs" }, + { name = "structs3", path = "exercises/07_structs/structs3.rs" }, + { name = "structs3_sol", path = "solutions/07_structs/structs3.rs" }, + { name = "enums1", path = "exercises/08_enums/enums1.rs" }, + { name = "enums1_sol", path = "solutions/08_enums/enums1.rs" }, + { name = "enums2", path = "exercises/08_enums/enums2.rs" }, + { name = "enums2_sol", path = "solutions/08_enums/enums2.rs" }, + { name = "enums3", path = "exercises/08_enums/enums3.rs" }, + { name = "enums3_sol", path = "solutions/08_enums/enums3.rs" }, + { name = "strings1", path = "exercises/09_strings/strings1.rs" }, + { name = "strings1_sol", path = "solutions/09_strings/strings1.rs" }, + { name = "strings2", path = "exercises/09_strings/strings2.rs" }, + { name = "strings2_sol", path = "solutions/09_strings/strings2.rs" }, + { name = "strings3", path = "exercises/09_strings/strings3.rs" }, + { name = "strings3_sol", path = "solutions/09_strings/strings3.rs" }, + { name = "strings4", path = "exercises/09_strings/strings4.rs" }, + { name = "strings4_sol", path = "solutions/09_strings/strings4.rs" }, + { name = "modules1", path = "exercises/10_modules/modules1.rs" }, + { name = "modules1_sol", path = "solutions/10_modules/modules1.rs" }, + { name = "modules2", path = "exercises/10_modules/modules2.rs" }, + { name = "modules2_sol", path = "solutions/10_modules/modules2.rs" }, + { name = "modules3", path = "exercises/10_modules/modules3.rs" }, + { name = "modules3_sol", path = "solutions/10_modules/modules3.rs" }, + { name = "hashmaps1", path = "exercises/11_hashmaps/hashmaps1.rs" }, + { name = "hashmaps1_sol", path = "solutions/11_hashmaps/hashmaps1.rs" }, + { name = "hashmaps2", path = "exercises/11_hashmaps/hashmaps2.rs" }, + { name = "hashmaps2_sol", path = "solutions/11_hashmaps/hashmaps2.rs" }, + { name = "hashmaps3", path = "exercises/11_hashmaps/hashmaps3.rs" }, + { name = "hashmaps3_sol", path = "solutions/11_hashmaps/hashmaps3.rs" }, + { name = "quiz2", path = "exercises/quizzes/quiz2.rs" }, + { name = "quiz2_sol", path = "solutions/quizzes/quiz2.rs" }, + { name = "options1", path = "exercises/12_options/options1.rs" }, + { name = "options1_sol", path = "solutions/12_options/options1.rs" }, + { name = "options2", path = "exercises/12_options/options2.rs" }, + { name = "options2_sol", path = "solutions/12_options/options2.rs" }, + { name = "options3", path = "exercises/12_options/options3.rs" }, + { name = "options3_sol", path = "solutions/12_options/options3.rs" }, + { name = "errors1", path = "exercises/13_error_handling/errors1.rs" }, + { name = "errors1_sol", path = "solutions/13_error_handling/errors1.rs" }, + { name = "errors2", path = "exercises/13_error_handling/errors2.rs" }, + { name = "errors2_sol", path = "solutions/13_error_handling/errors2.rs" }, + { name = "errors3", path = "exercises/13_error_handling/errors3.rs" }, + { name = "errors3_sol", path = "solutions/13_error_handling/errors3.rs" }, + { name = "errors4", path = "exercises/13_error_handling/errors4.rs" }, + { name = "errors4_sol", path = "solutions/13_error_handling/errors4.rs" }, + { name = "errors5", path = "exercises/13_error_handling/errors5.rs" }, + { name = "errors5_sol", path = "solutions/13_error_handling/errors5.rs" }, + { name = "errors6", path = "exercises/13_error_handling/errors6.rs" }, + { name = "errors6_sol", path = "solutions/13_error_handling/errors6.rs" }, + { name = "generics1", path = "exercises/14_generics/generics1.rs" }, + { name = "generics1_sol", path = "solutions/14_generics/generics1.rs" }, + { name = "generics2", path = "exercises/14_generics/generics2.rs" }, + { name = "generics2_sol", path = "solutions/14_generics/generics2.rs" }, + { name = "traits1", path = "exercises/15_traits/traits1.rs" }, + { name = "traits1_sol", path = "solutions/15_traits/traits1.rs" }, + { name = "traits2", path = "exercises/15_traits/traits2.rs" }, + { name = "traits2_sol", path = "solutions/15_traits/traits2.rs" }, + { name = "traits3", path = "exercises/15_traits/traits3.rs" }, + { name = "traits3_sol", path = "solutions/15_traits/traits3.rs" }, + { name = "traits4", path = "exercises/15_traits/traits4.rs" }, + { name = "traits4_sol", path = "solutions/15_traits/traits4.rs" }, + { name = "traits5", path = "exercises/15_traits/traits5.rs" }, + { name = "traits5_sol", path = "solutions/15_traits/traits5.rs" }, + { name = "quiz3", path = "exercises/quizzes/quiz3.rs" }, + { name = "quiz3_sol", path = "solutions/quizzes/quiz3.rs" }, + { name = "lifetimes1", path = "exercises/16_lifetimes/lifetimes1.rs" }, + { name = "lifetimes1_sol", path = "solutions/16_lifetimes/lifetimes1.rs" }, + { name = "lifetimes2", path = "exercises/16_lifetimes/lifetimes2.rs" }, + { name = "lifetimes2_sol", path = "solutions/16_lifetimes/lifetimes2.rs" }, + { name = "lifetimes3", path = "exercises/16_lifetimes/lifetimes3.rs" }, + { name = "lifetimes3_sol", path = "solutions/16_lifetimes/lifetimes3.rs" }, + { name = "tests1", path = "exercises/17_tests/tests1.rs" }, + { name = "tests1_sol", path = "solutions/17_tests/tests1.rs" }, + { name = "tests2", path = "exercises/17_tests/tests2.rs" }, + { name = "tests2_sol", path = "solutions/17_tests/tests2.rs" }, + { name = "tests3", path = "exercises/17_tests/tests3.rs" }, + { name = "tests3_sol", path = "solutions/17_tests/tests3.rs" }, + { name = "iterators1", path = "exercises/18_iterators/iterators1.rs" }, + { name = "iterators1_sol", path = "solutions/18_iterators/iterators1.rs" }, + { name = "iterators2", path = "exercises/18_iterators/iterators2.rs" }, + { name = "iterators2_sol", path = "solutions/18_iterators/iterators2.rs" }, + { name = "iterators3", path = "exercises/18_iterators/iterators3.rs" }, + { name = "iterators3_sol", path = "solutions/18_iterators/iterators3.rs" }, + { name = "iterators4", path = "exercises/18_iterators/iterators4.rs" }, + { name = "iterators4_sol", path = "solutions/18_iterators/iterators4.rs" }, + { name = "iterators5", path = "exercises/18_iterators/iterators5.rs" }, + { name = "iterators5_sol", path = "solutions/18_iterators/iterators5.rs" }, + { name = "box1", path = "exercises/19_smart_pointers/box1.rs" }, + { name = "box1_sol", path = "solutions/19_smart_pointers/box1.rs" }, + { name = "rc1", path = "exercises/19_smart_pointers/rc1.rs" }, + { name = "rc1_sol", path = "solutions/19_smart_pointers/rc1.rs" }, + { name = "arc1", path = "exercises/19_smart_pointers/arc1.rs" }, + { name = "arc1_sol", path = "solutions/19_smart_pointers/arc1.rs" }, + { name = "cow1", path = "exercises/19_smart_pointers/cow1.rs" }, + { name = "cow1_sol", path = "solutions/19_smart_pointers/cow1.rs" }, + { name = "threads1", path = "exercises/20_threads/threads1.rs" }, + { name = "threads1_sol", path = "solutions/20_threads/threads1.rs" }, + { name = "threads2", path = "exercises/20_threads/threads2.rs" }, + { name = "threads2_sol", path = "solutions/20_threads/threads2.rs" }, + { name = "threads3", path = "exercises/20_threads/threads3.rs" }, + { name = "threads3_sol", path = "solutions/20_threads/threads3.rs" }, + { name = "macros1", path = "exercises/21_macros/macros1.rs" }, + { name = "macros1_sol", path = "solutions/21_macros/macros1.rs" }, + { name = "macros2", path = "exercises/21_macros/macros2.rs" }, + { name = "macros2_sol", path = "solutions/21_macros/macros2.rs" }, + { name = "macros3", path = "exercises/21_macros/macros3.rs" }, + { name = "macros3_sol", path = "solutions/21_macros/macros3.rs" }, + { name = "macros4", path = "exercises/21_macros/macros4.rs" }, + { name = "macros4_sol", path = "solutions/21_macros/macros4.rs" }, + { name = "clippy1", path = "exercises/22_clippy/clippy1.rs" }, + { name = "clippy1_sol", path = "solutions/22_clippy/clippy1.rs" }, + { name = "clippy2", path = "exercises/22_clippy/clippy2.rs" }, + { name = "clippy2_sol", path = "solutions/22_clippy/clippy2.rs" }, + { name = "clippy3", path = "exercises/22_clippy/clippy3.rs" }, + { name = "clippy3_sol", path = "solutions/22_clippy/clippy3.rs" }, + { name = "using_as", path = "exercises/23_conversions/using_as.rs" }, + { name = "using_as_sol", path = "solutions/23_conversions/using_as.rs" }, + { name = "from_into", path = "exercises/23_conversions/from_into.rs" }, + { name = "from_into_sol", path = "solutions/23_conversions/from_into.rs" }, + { name = "from_str", path = "exercises/23_conversions/from_str.rs" }, + { name = "from_str_sol", path = "solutions/23_conversions/from_str.rs" }, + { name = "try_from_into", path = "exercises/23_conversions/try_from_into.rs" }, + { name = "try_from_into_sol", path = "solutions/23_conversions/try_from_into.rs" }, + { name = "as_ref_mut", path = "exercises/23_conversions/as_ref_mut.rs" }, + { name = "as_ref_mut_sol", path = "solutions/23_conversions/as_ref_mut.rs" }, +] + +[package] +name = "exercises" +edition = "2024" +# Don't publish the exercises on crates.io! +publish = false + +[profile.release] +panic = "abort" + +[profile.dev] +panic = "abort" + +[lints.rust] +# You shouldn't write unsafe code in Rustlings! +unsafe_code = "forbid" +# You don't need unstable features in Rustlings and shouldn't rely on them while learning Rust. +unstable_features = "forbid" +# Dead code warnings can't be avoided in some exercises and might distract while learning. +dead_code = "allow" + +[lints.clippy] +# You forgot a `todo!()`! +todo = "forbid" +# This can only happen by mistake in Rustlings. +empty_loop = "forbid" +# No infinite loops are needed in Rustlings. +infinite_loop = "deny" +# You shouldn't leak memory while still learning Rust! +mem_forget = "deny" +# Currently, there are no disallowed methods. This line avoids problems when developing Rustlings. +disallowed_methods = "allow" diff --git a/rust/rustlings/exercises/00_intro/README.md b/rust/rustlings/exercises/00_intro/README.md new file mode 100644 index 0000000..d32e4a8 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/00_intro/intro1.rs b/rust/rustlings/exercises/00_intro/intro1.rs new file mode 100644 index 0000000..440ae83 --- /dev/null +++ b/rust/rustlings/exercises/00_intro/intro1.rs @@ -0,0 +1,28 @@ +// TODO: 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, enter `n` in the terminal. +// +// The exercise file will be reloaded when you change one of the lines below! +// Try adding a new `println!` and check the updated output in the terminal. + +fn main() { + 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 file of this exercise is `exercises/00_intro/intro1.rs`. Have a look!"); + println!("The current exercise path will be always shown under the progress bar."); + println!("You can click on the path to open the exercise file in your editor."); + println!(); + println!("New line"); + println!( " another line "); + println!(r#" yet another line"#); +} diff --git a/rust/rustlings/exercises/00_intro/intro2.rs b/rust/rustlings/exercises/00_intro/intro2.rs new file mode 100644 index 0000000..e0b5e27 --- /dev/null +++ b/rust/rustlings/exercises/00_intro/intro2.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello world!"); +} diff --git a/rust/rustlings/exercises/01_variables/README.md b/rust/rustlings/exercises/01_variables/README.md new file mode 100644 index 0000000..5ba2efc --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/01_variables/variables1.rs b/rust/rustlings/exercises/01_variables/variables1.rs new file mode 100644 index 0000000..2df7df8 --- /dev/null +++ b/rust/rustlings/exercises/01_variables/variables1.rs @@ -0,0 +1,5 @@ +fn main() { + let x = 5; + + println!("x has the value {x}"); +} diff --git a/rust/rustlings/exercises/01_variables/variables2.rs b/rust/rustlings/exercises/01_variables/variables2.rs new file mode 100644 index 0000000..b35a0bf --- /dev/null +++ b/rust/rustlings/exercises/01_variables/variables2.rs @@ -0,0 +1,9 @@ +fn main() { + let x = 10; + + if x == 10 { + println!("x is ten!"); + } else { + println!("x is not ten!"); + } +} diff --git a/rust/rustlings/exercises/01_variables/variables3.rs b/rust/rustlings/exercises/01_variables/variables3.rs new file mode 100644 index 0000000..47b2be4 --- /dev/null +++ b/rust/rustlings/exercises/01_variables/variables3.rs @@ -0,0 +1,5 @@ +fn main() { + let x = 10; + + println!("Number {x}"); +} diff --git a/rust/rustlings/exercises/01_variables/variables4.rs b/rust/rustlings/exercises/01_variables/variables4.rs new file mode 100644 index 0000000..d2967ea --- /dev/null +++ b/rust/rustlings/exercises/01_variables/variables4.rs @@ -0,0 +1,7 @@ +fn main() { + let mut x = 3; + println!("Number {x}"); + + x = 5; // Don't change this line + println!("Number {x}"); +} diff --git a/rust/rustlings/exercises/01_variables/variables5.rs b/rust/rustlings/exercises/01_variables/variables5.rs new file mode 100644 index 0000000..be94598 --- /dev/null +++ b/rust/rustlings/exercises/01_variables/variables5.rs @@ -0,0 +1,7 @@ +fn main() { + let number = "T-H-R-E-E"; // Don't change this line + println!("Spell a number: {number}"); + + let number = 3; + println!("Number plus two is: {}", number + 2); +} diff --git a/rust/rustlings/exercises/01_variables/variables6.rs b/rust/rustlings/exercises/01_variables/variables6.rs new file mode 100644 index 0000000..c40e572 --- /dev/null +++ b/rust/rustlings/exercises/01_variables/variables6.rs @@ -0,0 +1,5 @@ +const NUMBER: i32 = 3; + +fn main() { + println!("Number: {NUMBER}"); +} diff --git a/rust/rustlings/exercises/02_functions/README.md b/rust/rustlings/exercises/02_functions/README.md new file mode 100644 index 0000000..6662d0d --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/02_functions/functions1.rs b/rust/rustlings/exercises/02_functions/functions1.rs new file mode 100644 index 0000000..5dbae07 --- /dev/null +++ b/rust/rustlings/exercises/02_functions/functions1.rs @@ -0,0 +1,7 @@ +fn call_me() { + println!("call_me()"); +} + +fn main() { + call_me(); // Don't change this line +} diff --git a/rust/rustlings/exercises/02_functions/functions2.rs b/rust/rustlings/exercises/02_functions/functions2.rs new file mode 100644 index 0000000..27f2cc7 --- /dev/null +++ b/rust/rustlings/exercises/02_functions/functions2.rs @@ -0,0 +1,9 @@ +fn call_me(num: u32) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + call_me(3); +} diff --git a/rust/rustlings/exercises/02_functions/functions3.rs b/rust/rustlings/exercises/02_functions/functions3.rs new file mode 100644 index 0000000..88dff5b --- /dev/null +++ b/rust/rustlings/exercises/02_functions/functions3.rs @@ -0,0 +1,9 @@ +fn call_me(num: u8) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + call_me(3); +} diff --git a/rust/rustlings/exercises/02_functions/functions4.rs b/rust/rustlings/exercises/02_functions/functions4.rs new file mode 100644 index 0000000..2c5a3b0 --- /dev/null +++ b/rust/rustlings/exercises/02_functions/functions4.rs @@ -0,0 +1,17 @@ +fn is_even(num: i64) -> bool { + num % 2 == 0 +} + +// TODO: Fix the function signature. +fn sale_price(price: i64) -> i64 { + if is_even(price) { + price - 10 + } else { + price - 3 + } +} + +fn main() { + let original_price = 51; + println!("Your sale price is {}", sale_price(original_price)); +} diff --git a/rust/rustlings/exercises/02_functions/functions5.rs b/rust/rustlings/exercises/02_functions/functions5.rs new file mode 100644 index 0000000..024010f --- /dev/null +++ b/rust/rustlings/exercises/02_functions/functions5.rs @@ -0,0 +1,8 @@ +fn square(num: i32) -> i32 { + num * num +} + +fn main() { + let answer = square(3); + println!("The square of 3 is {answer}"); +} diff --git a/rust/rustlings/exercises/03_if/README.md b/rust/rustlings/exercises/03_if/README.md new file mode 100644 index 0000000..b52c392 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/03_if/if1.rs b/rust/rustlings/exercises/03_if/if1.rs new file mode 100644 index 0000000..079c671 --- /dev/null +++ b/rust/rustlings/exercises/03_if/if1.rs @@ -0,0 +1,32 @@ +fn bigger(a: i32, b: i32) -> i32 { + if a > b { + a + } else { + b + } +} + +fn main() { + // You can optionally experiment here. +} + +// 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/rust/rustlings/exercises/03_if/if2.rs b/rust/rustlings/exercises/03_if/if2.rs new file mode 100644 index 0000000..8104487 --- /dev/null +++ b/rust/rustlings/exercises/03_if/if2.rs @@ -0,0 +1,39 @@ +// TODO: Fix the compiler error on this function. +fn picky_eater(food: &str) -> &str { + if food == "strawberry" { + "Yummy!" + } else if food == "potato" { + "I guess I can eat that." + } else { + "No thanks!" + } +} + +fn main() { + // You can optionally experiment here. +} + +// TODO: Read the tests to understand the desired behavior. +// Make all tests pass without changing them. +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn yummy_food() { + // This means that calling `picky_eater` with the argument "strawberry" should return "Yummy!". + assert_eq!(picky_eater("strawberry"), "Yummy!"); + } + + #[test] + fn neutral_food() { + assert_eq!(picky_eater("potato"), "I guess I can eat that."); + } + + #[test] + fn default_disliked_food() { + assert_eq!(picky_eater("broccoli"), "No thanks!"); + assert_eq!(picky_eater("gummy bears"), "No thanks!"); + assert_eq!(picky_eater("literally anything"), "No thanks!"); + } +} diff --git a/rust/rustlings/exercises/03_if/if3.rs b/rust/rustlings/exercises/03_if/if3.rs new file mode 100644 index 0000000..fee96f8 --- /dev/null +++ b/rust/rustlings/exercises/03_if/if3.rs @@ -0,0 +1,52 @@ +fn animal_habitat(animal: &str) -> &str { + let identifier = if animal == "crab" { + 1 + } else if animal == "gopher" { + 2 + } else if animal == "snake" { + 3 + } else { + 0 + }; + + // Don't change the expression below! + if identifier == 1 { + "Beach" + } else if identifier == 2 { + "Burrow" + } else if identifier == 3 { + "Desert" + } else { + "Unknown" + } +} + +fn main() { + // You can optionally experiment here. +} + +// Don't change the tests! +#[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/rust/rustlings/exercises/04_primitive_types/README.md b/rust/rustlings/exercises/04_primitive_types/README.md new file mode 100644 index 0000000..d67668a --- /dev/null +++ b/rust/rustlings/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/book/ch03-02-data-types.html) +- [The Slice Type](https://doc.rust-lang.org/book/ch04-03-slices.html) diff --git a/rust/rustlings/exercises/04_primitive_types/primitive_types1.rs b/rust/rustlings/exercises/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000..778c0f6 --- /dev/null +++ b/rust/rustlings/exercises/04_primitive_types/primitive_types1.rs @@ -0,0 +1,13 @@ +// Booleans (`bool`) + +fn main() { + let is_morning = true; + if is_morning { + println!("Good morning!"); + } + + let is_evening = !is_morning; + if is_evening { + println!("Good evening!"); + } +} diff --git a/rust/rustlings/exercises/04_primitive_types/primitive_types2.rs b/rust/rustlings/exercises/04_primitive_types/primitive_types2.rs new file mode 100644 index 0000000..a45f84d --- /dev/null +++ b/rust/rustlings/exercises/04_primitive_types/primitive_types2.rs @@ -0,0 +1,23 @@ +// Characters (`char`) + +fn main() { + // 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 your_character = '😉'; + if your_character.is_alphabetic() { + println!("Alphabetical!"); + } else if your_character.is_numeric() { + println!("Numerical!"); + } else { + println!("Neither alphabetic nor numeric!"); + } +} diff --git a/rust/rustlings/exercises/04_primitive_types/primitive_types3.rs b/rust/rustlings/exercises/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000..c5a259d --- /dev/null +++ b/rust/rustlings/exercises/04_primitive_types/primitive_types3.rs @@ -0,0 +1,10 @@ +fn main() { + let a = [0; 1000]; + + 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/rust/rustlings/exercises/04_primitive_types/primitive_types4.rs b/rust/rustlings/exercises/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000..81af3e2 --- /dev/null +++ b/rust/rustlings/exercises/04_primitive_types/primitive_types4.rs @@ -0,0 +1,15 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn slice_out_of_array() { + let a = [1, 2, 3, 4, 5]; + + let nice_slice = &a[1..4]; + + assert_eq!([2, 3, 4], nice_slice); + } +} diff --git a/rust/rustlings/exercises/04_primitive_types/primitive_types5.rs b/rust/rustlings/exercises/04_primitive_types/primitive_types5.rs new file mode 100644 index 0000000..a3e60d8 --- /dev/null +++ b/rust/rustlings/exercises/04_primitive_types/primitive_types5.rs @@ -0,0 +1,7 @@ +fn main() { + let cat = ("Furry McFurson", 3.5); + + let (name, age) = cat; + + println!("{name} is {age} years old"); +} diff --git a/rust/rustlings/exercises/04_primitive_types/primitive_types6.rs b/rust/rustlings/exercises/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000..dec639a --- /dev/null +++ b/rust/rustlings/exercises/04_primitive_types/primitive_types6.rs @@ -0,0 +1,15 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn indexing_tuple() { + let numbers = (1, 2, 3); + + let second = numbers.1; + + assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); + } +} diff --git a/rust/rustlings/exercises/05_vecs/README.md b/rust/rustlings/exercises/05_vecs/README.md new file mode 100644 index 0000000..e1b6128 --- /dev/null +++ b/rust/rustlings/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/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/rust/rustlings/exercises/05_vecs/vecs1.rs b/rust/rustlings/exercises/05_vecs/vecs1.rs new file mode 100644 index 0000000..f976c84 --- /dev/null +++ b/rust/rustlings/exercises/05_vecs/vecs1.rs @@ -0,0 +1,22 @@ +fn array_and_vec() -> ([i32; 4], Vec) { + let a = [10, 20, 30, 40]; // Array + + let v = vec![10, 20, 30, 40]; + + (a, v) +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/exercises/05_vecs/vecs2.rs b/rust/rustlings/exercises/05_vecs/vecs2.rs new file mode 100644 index 0000000..1ec77f7 --- /dev/null +++ b/rust/rustlings/exercises/05_vecs/vecs2.rs @@ -0,0 +1,61 @@ +fn vec_loop(input: &[i32]) -> Vec { + let mut output = Vec::new(); + + for element in input { + // TODO: Multiply each element in the `input` slice by 2 and push it to + // the `output` vector. + output.push(element * 2); + } + + output +} + +fn vec_map_example(input: &[i32]) -> Vec { + // An example of collecting a vector after mapping. + // We map each element of the `input` slice to its value plus 1. + // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`. + input.iter().map(|element| element + 1).collect() +} + +fn vec_map(input: &[i32]) -> Vec { + // TODO: Here, we also want to multiply each element in the `input` slice + // by 2, but with iterator mapping instead of manually pushing into an empty + // vector. + // See the example in the function `vec_map_example` above. + input + .iter() + .map(|element| { + element * 2 + }) + .collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec_loop() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_loop(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } + + #[test] + fn test_vec_map_example() { + let input = [1, 2, 3]; + let ans = vec_map_example(&input); + assert_eq!(ans, [2, 3, 4]); + } + + #[test] + fn test_vec_map() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_map(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } +} diff --git a/rust/rustlings/exercises/06_move_semantics/README.md b/rust/rustlings/exercises/06_move_semantics/README.md new file mode 100644 index 0000000..54ddd8e --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/06_move_semantics/move_semantics1.rs b/rust/rustlings/exercises/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000..9385f28 --- /dev/null +++ b/rust/rustlings/exercises/06_move_semantics/move_semantics1.rs @@ -0,0 +1,23 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics1() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + assert_eq!(vec1, vec![22, 44, 66, 88]); + } +} diff --git a/rust/rustlings/exercises/06_move_semantics/move_semantics2.rs b/rust/rustlings/exercises/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000..e205b81 --- /dev/null +++ b/rust/rustlings/exercises/06_move_semantics/move_semantics2.rs @@ -0,0 +1,28 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + // TODO: Make both vectors `vec0` and `vec1` accessible at the same time to + // fix the compiler error in the test. + #[test] + fn move_semantics2() { + let vec0 = vec![22, 44, 66]; + + let vec1 = fill_vec(vec0.clone()); + + assert_eq!(vec0, [22, 44, 66]); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/rust/rustlings/exercises/06_move_semantics/move_semantics3.rs b/rust/rustlings/exercises/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000..4a90c21 --- /dev/null +++ b/rust/rustlings/exercises/06_move_semantics/move_semantics3.rs @@ -0,0 +1,22 @@ +// TODO: Fix the compiler error in the function without adding any new line. +fn fill_vec(mut vec: Vec) -> Vec { + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics3() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/rust/rustlings/exercises/06_move_semantics/move_semantics4.rs b/rust/rustlings/exercises/06_move_semantics/move_semantics4.rs new file mode 100644 index 0000000..89b412f --- /dev/null +++ b/rust/rustlings/exercises/06_move_semantics/move_semantics4.rs @@ -0,0 +1,18 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // TODO: Fix the compiler errors only by reordering the lines in the test. + // Don't add, change or remove any line. + #[test] + fn move_semantics4() { + let mut x = Vec::new(); + let y = &mut x; + y.push(42); + let z = &mut x; + z.push(13); + assert_eq!(x, [42, 13]); + } +} diff --git a/rust/rustlings/exercises/06_move_semantics/move_semantics5.rs b/rust/rustlings/exercises/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000..78d8c77 --- /dev/null +++ b/rust/rustlings/exercises/06_move_semantics/move_semantics5.rs @@ -0,0 +1,24 @@ +#![allow(clippy::ptr_arg)] + +// TODO: Fix the compiler errors without changing anything except adding or +// removing references (the character `&`). + +// Shouldn't 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}"); +} + +fn main() { + let data = "Rust is great!".to_string(); + + get_char(&data); + + string_uppercase(data); +} diff --git a/rust/rustlings/exercises/07_structs/README.md b/rust/rustlings/exercises/07_structs/README.md new file mode 100644 index 0000000..3fc1fdc --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/07_structs/structs1.rs b/rust/rustlings/exercises/07_structs/structs1.rs new file mode 100644 index 0000000..8376a98 --- /dev/null +++ b/rust/rustlings/exercises/07_structs/structs1.rs @@ -0,0 +1,50 @@ +struct ColorRegularStruct { + red: u8, + green: u8, + blue: u8, +} + +struct ColorTupleStruct(u8, u8, u8); + +#[derive(Debug)] +struct UnitStruct; + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn regular_structs() { + let green = ColorRegularStruct { + red: 0, + green: 255, + blue: 0, + }; + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + let green = ColorTupleStruct(0, 255, 0 ); + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + let unit_struct = UnitStruct; + + let message = format!("{unit_struct:?}s are fun!"); + + assert_eq!(message, "UnitStructs are fun!"); + } +} diff --git a/rust/rustlings/exercises/07_structs/structs2.rs b/rust/rustlings/exercises/07_structs/structs2.rs new file mode 100644 index 0000000..2539e31 --- /dev/null +++ b/rust/rustlings/exercises/07_structs/structs2.rs @@ -0,0 +1,50 @@ +#[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, + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn your_order() { + let order_template = create_order_template(); + + let your_order = Order { + name: String::from("Hacker in Rust"), + count: 1, + ..order_template + }; + + assert_eq!(your_order.name, "Hacker in Rust"); + assert_eq!(your_order.year, order_template.year); + assert_eq!(your_order.made_by_phone, order_template.made_by_phone); + 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/rust/rustlings/exercises/07_structs/structs3.rs b/rust/rustlings/exercises/07_structs/structs3.rs new file mode 100644 index 0000000..d24da27 --- /dev/null +++ b/rust/rustlings/exercises/07_structs/structs3.rs @@ -0,0 +1,84 @@ +// 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. + +#[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) -> Self { + if weight_in_grams < 10 { + // This isn't how you should handle errors in Rust, but we will + // learn about error handling later. + panic!("Can't ship a package with weight below 10 grams"); + } + + Self { + sender_country, + recipient_country, + weight_in_grams, + } + } + + fn is_international(&self) -> bool { + self.sender_country != self.recipient_country + } + + fn get_fees(&self, cents_per_gram: u32) -> u32 { + self.weight_in_grams * cents_per_gram + } +} + +fn main() { + // You can optionally experiment 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/rust/rustlings/exercises/08_enums/README.md b/rust/rustlings/exercises/08_enums/README.md new file mode 100644 index 0000000..b05cb42 --- /dev/null +++ b/rust/rustlings/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/ch19-03-pattern-syntax.html) diff --git a/rust/rustlings/exercises/08_enums/enums1.rs b/rust/rustlings/exercises/08_enums/enums1.rs new file mode 100644 index 0000000..97a5cc0 --- /dev/null +++ b/rust/rustlings/exercises/08_enums/enums1.rs @@ -0,0 +1,16 @@ +#[derive(Debug)] +enum Message { + Resize, + Move, + Echo, + ChangeColor, + Quit, +} + +fn main() { + println!("{:?}", Message::Resize); + println!("{:?}", Message::Move); + println!("{:?}", Message::Echo); + println!("{:?}", Message::ChangeColor); + println!("{:?}", Message::Quit); +} diff --git a/rust/rustlings/exercises/08_enums/enums2.rs b/rust/rustlings/exercises/08_enums/enums2.rs new file mode 100644 index 0000000..4a2d5ac --- /dev/null +++ b/rust/rustlings/exercises/08_enums/enums2.rs @@ -0,0 +1,40 @@ +#[derive(Debug)] +struct Point { + x: u64, + y: u64, +} + +#[derive(Debug)] +enum Message { + Resize { + width: u64, + height: u64, + }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +impl Message { + fn call(&self) { + println!("{self:?}"); + } +} + +fn main() { + let messages = [ + Message::Resize { + width: 10, + height: 30, + }, + Message::Move(Point { x: 10, y: 15 }), + Message::Echo(String::from("hello world")), + Message::ChangeColor(200, 255, 255), + Message::Quit, + ]; + + for message in &messages { + message.call(); + } +} diff --git a/rust/rustlings/exercises/08_enums/enums3.rs b/rust/rustlings/exercises/08_enums/enums3.rs new file mode 100644 index 0000000..bf01af3 --- /dev/null +++ b/rust/rustlings/exercises/08_enums/enums3.rs @@ -0,0 +1,93 @@ +struct Point { + x: u64, + y: u64, +} + +enum Message { + Resize { width: u64, height: u64 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +struct State { + width: u64, + height: u64, + position: Point, + message: String, + // RGB color composed of red, green and blue. + color: (u8, u8, u8), + quit: bool, +} + +impl State { + fn resize(&mut self, width: u64, height: u64) { + self.width = width; + self.height = height; + } + + fn move_position(&mut self, point: Point) { + self.position = point; + } + + fn echo(&mut self, s: String) { + self.message = s; + } + + fn change_color(&mut self, red: u8, green: u8, blue: u8) { + self.color = (red, green, blue); + } + + fn quit(&mut self) { + self.quit = true; + } + + fn process(&mut self, message: Message) { + match message { + Message::Resize { width, height } => self.resize(width, height), + Message::Move(point) => self.move_position(point), + Message::Echo(s) => self.echo(s), + Message::ChangeColor(red, green, blue) => self.change_color(red, green, blue), + Message::Quit => self.quit(), + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_match_message_call() { + let mut state = State { + width: 0, + height: 0, + position: Point { x: 0, y: 0 }, + message: String::from("hello world"), + color: (0, 0, 0), + quit: false, + }; + + state.process(Message::Resize { + width: 10, + height: 30, + }); + state.process(Message::Move(Point { x: 10, y: 15 })); + state.process(Message::Echo(String::from("Hello world!"))); + state.process(Message::ChangeColor(255, 0, 255)); + state.process(Message::Quit); + + assert_eq!(state.width, 10); + assert_eq!(state.height, 30); + assert_eq!(state.position.x, 10); + assert_eq!(state.position.y, 15); + assert_eq!(state.message, "Hello world!"); + assert_eq!(state.color, (255, 0, 255)); + assert!(state.quit); + } +} diff --git a/rust/rustlings/exercises/09_strings/README.md b/rust/rustlings/exercises/09_strings/README.md new file mode 100644 index 0000000..fa2104c --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/09_strings/strings1.rs b/rust/rustlings/exercises/09_strings/strings1.rs new file mode 100644 index 0000000..482e5de --- /dev/null +++ b/rust/rustlings/exercises/09_strings/strings1.rs @@ -0,0 +1,8 @@ +fn current_favorite_color() -> String { + String::from("blue") +} + +fn main() { + let answer = current_favorite_color(); + println!("My current favorite color is {answer}"); +} diff --git a/rust/rustlings/exercises/09_strings/strings2.rs b/rust/rustlings/exercises/09_strings/strings2.rs new file mode 100644 index 0000000..b03094f --- /dev/null +++ b/rust/rustlings/exercises/09_strings/strings2.rs @@ -0,0 +1,13 @@ +fn is_a_color_word(attempt: &str) -> bool { + attempt == "green" || attempt == "blue" || attempt == "red" +} + +fn main() { + let word = String::from("green"); // Don't change 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."); + } +} diff --git a/rust/rustlings/exercises/09_strings/strings3.rs b/rust/rustlings/exercises/09_strings/strings3.rs new file mode 100644 index 0000000..3543ad5 --- /dev/null +++ b/rust/rustlings/exercises/09_strings/strings3.rs @@ -0,0 +1,46 @@ +fn trim_me(input: &str) -> &str { + input.trim() +} + +fn compose_me(input: &str) -> String { + String::from(input) + " world!" +} + +fn replace_me(input: &str) -> String { + String::from(input).replace("cars", "balloons") +} + +fn main() { + // You can optionally experiment here. +} + +#[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!"); + assert_eq!(trim_me("Hi!"), "Hi!"); + } + + #[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/rust/rustlings/exercises/09_strings/strings4.rs b/rust/rustlings/exercises/09_strings/strings4.rs new file mode 100644 index 0000000..3f7c5e7 --- /dev/null +++ b/rust/rustlings/exercises/09_strings/strings4.rs @@ -0,0 +1,37 @@ +// Calls of this function should be replaced with calls of `string_slice` or `string`. +fn placeholder() {} + +fn string_slice(arg: &str) { + println!("{arg}"); +} + +fn string(arg: String) { + println!("{arg}"); +} + +// TODO: Here are a bunch of values - some are `String`, some are `&str`. +// Your task is to replace `placeholder(…)` with either `string_slice(…)` +// or `string(…)` depending on what you think each value is. +fn main() { + string_slice("blue"); + + string("red".to_string()); + + string(String::from("hi")); + + string("rust is fun!".to_owned()); + + string("nice weather".into()); + + string(format!("Interpolation {}", "Station")); + + // WARNING: This is byte indexing, not character indexing. + // Character indexing can be done using `s.chars().nth(INDEX)`. + string_slice(&String::from("abc")[0..1]); + + string_slice(" hello there ".trim()); + + string("Happy Monday!".replace("Mon", "Tues")); + + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); +} diff --git a/rust/rustlings/exercises/10_modules/README.md b/rust/rustlings/exercises/10_modules/README.md new file mode 100644 index 0000000..3dc8a48 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/10_modules/modules1.rs b/rust/rustlings/exercises/10_modules/modules1.rs new file mode 100644 index 0000000..0d7c5a2 --- /dev/null +++ b/rust/rustlings/exercises/10_modules/modules1.rs @@ -0,0 +1,15 @@ +mod sausage_factory { + // Don't let anybody outside of this module see this! + fn get_secret_recipe() -> String { + String::from("Ginger") + } + + pub fn make_sausage() { + get_secret_recipe(); + println!("sausage!"); + } +} + +fn main() { + sausage_factory::make_sausage(); +} diff --git a/rust/rustlings/exercises/10_modules/modules2.rs b/rust/rustlings/exercises/10_modules/modules2.rs new file mode 100644 index 0000000..3cabbfd --- /dev/null +++ b/rust/rustlings/exercises/10_modules/modules2.rs @@ -0,0 +1,26 @@ +// You can bring module paths into scopes and provide new names for them with +// the `use` and `as` keywords. + +mod delicious_snacks { + // TODO: Add the following two `use` statements after fixing them. + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; + + mod fruits { + pub const PEAR: &str = "Pear"; + pub const APPLE: &str = "Apple"; + } + + mod veggies { + pub const CUCUMBER: &str = "Cucumber"; + pub const CARROT: &str = "Carrot"; + } +} + +fn main() { + println!( + "favorite snacks: {} and {}", + delicious_snacks::fruit, + delicious_snacks::veggie, + ); +} diff --git a/rust/rustlings/exercises/10_modules/modules3.rs b/rust/rustlings/exercises/10_modules/modules3.rs new file mode 100644 index 0000000..403b7ea --- /dev/null +++ b/rust/rustlings/exercises/10_modules/modules3.rs @@ -0,0 +1,13 @@ +// You can use the `use` keyword to bring module paths from modules from +// anywhere and especially from the standard library into your scope. + +// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into +// your scope. Bonus style points if you can do it with one line! +use std::time::{SystemTime, UNIX_EPOCH}; + +fn main() { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), + Err(_) => panic!("SystemTime before UNIX EPOCH!"), + } +} diff --git a/rust/rustlings/exercises/11_hashmaps/README.md b/rust/rustlings/exercises/11_hashmaps/README.md new file mode 100644 index 0000000..80ec144 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/11_hashmaps/hashmaps1.rs b/rust/rustlings/exercises/11_hashmaps/hashmaps1.rs new file mode 100644 index 0000000..a746b32 --- /dev/null +++ b/rust/rustlings/exercises/11_hashmaps/hashmaps1.rs @@ -0,0 +1,43 @@ +// 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 3 different +// types of fruits (e.g. apple, banana, mango) in the basket and the total count +// of all the fruits should be at least 5. + +use std::collections::HashMap; + +fn fruit_basket() -> HashMap { + // TODO: Declare the hash map. + let mut basket = HashMap::new(); + + // Two bananas are already given for you :) + basket.insert(String::from("banana"), 2); + + // TODO: Put more fruits in your basket. + basket.insert(String::from("banana"), 1); + basket.insert(String::from("orange"), 140000); + basket.insert(String::from("strawberry"), 5); + + basket +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/exercises/11_hashmaps/hashmaps2.rs b/rust/rustlings/exercises/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000..482db7c --- /dev/null +++ b/rust/rustlings/exercises/11_hashmaps/hashmaps2.rs @@ -0,0 +1,99 @@ +// 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 the fruits that are already in the basket (Apple, +// Mango, and Lychee). + +use std::collections::HashMap; + +#[derive(Hash, PartialEq, Eq, Debug)] +enum Fruit { + Apple, + Banana, + Mango, + Lychee, + Pineapple, +} + +fn fruit_basket(basket: &mut HashMap) { + let fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + for fruit in fruit_kinds { + // This works just fine, but clippy doesn't like how readable and obvious the code is + // if !basket.contains_key(&fruit) { + // basket.insert(fruit, 10); + // } + basket.entry(fruit).or_insert(10); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + // Don't modify this function! + fn get_fruit_basket() -> HashMap { + let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)]; + HashMap::from_iter(content) + } + + #[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 fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + + for fruit_kind in fruit_kinds { + let Some(amount) = basket.get(&fruit_kind) else { + panic!("Fruit kind {fruit_kind:?} was not found in basket"); + }; + assert!(*amount > 0); + } + } +} diff --git a/rust/rustlings/exercises/11_hashmaps/hashmaps3.rs b/rust/rustlings/exercises/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000..0fa4a6b --- /dev/null +++ b/rust/rustlings/exercises/11_hashmaps/hashmaps3.rs @@ -0,0 +1,84 @@ +// 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, the total +// number of goals the team scored, and the total number of goals the team +// conceded. + +use std::collections::HashMap; + +// A structure to store the goal details of a team. +#[derive(Default)] +struct TeamScores { + goals_scored: u8, + goals_conceded: u8, +} + +fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { + // The name of the team is the key and its associated struct is the value. + let mut scores = HashMap::<&str, TeamScores>::new(); + + for line in results.lines() { + let mut split_iterator = line.split(','); + // NOTE: We use `unwrap` because we didn't deal with error handling yet. + let team_1_name = split_iterator.next().unwrap(); + let team_2_name = split_iterator.next().unwrap(); + let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + + // TODO: Populate the scores table with the extracted details. + // Keep in mind that goals scored by team 1 will be the number of goals + // conceded by team 2. Similarly, goals scored by team 2 will be the + // number of goals conceded by team 1. + let team_1 = scores.entry(team_1_name).or_default(); + team_1.goals_scored += team_1_score; + team_1.goals_conceded += team_2_score; + let team_2 = scores.entry(team_2_name).or_default(); + team_2.goals_scored += team_2_score; + team_2.goals_conceded += team_1_score; + + } + + scores +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + const RESULTS: &str = "England,France,4,2 +France,Italy,3,1 +Poland,Spain,2,0 +Germany,England,2,1 +England,Spain,1,0"; + + #[test] + fn build_scores() { + let scores = build_scores_table(RESULTS); + + assert!(["England", "France", "Germany", "Italy", "Poland", "Spain"] + .into_iter() + .all(|team_name| scores.contains_key(team_name))); + } + + #[test] + fn validate_team_score_1() { + let scores = build_scores_table(RESULTS); + let team = scores.get("England").unwrap(); + assert_eq!(team.goals_scored, 6); + assert_eq!(team.goals_conceded, 4); + } + + #[test] + fn validate_team_score_2() { + let scores = build_scores_table(RESULTS); + let team = scores.get("Spain").unwrap(); + assert_eq!(team.goals_scored, 0); + assert_eq!(team.goals_conceded, 3); + } +} diff --git a/rust/rustlings/exercises/12_options/README.md b/rust/rustlings/exercises/12_options/README.md new file mode 100644 index 0000000..624572a --- /dev/null +++ b/rust/rustlings/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/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/rust/rustlings/exercises/12_options/options1.rs b/rust/rustlings/exercises/12_options/options1.rs new file mode 100644 index 0000000..be97952 --- /dev/null +++ b/rust/rustlings/exercises/12_options/options1.rs @@ -0,0 +1,42 @@ +// This function returns how much ice cream there is left in the fridge. +// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, +// someone eats it all, so no ice cream is left (value 0). Return `None` if +// `hour_of_day` is higher than 23. +fn maybe_ice_cream(hour_of_day: u16) -> Option { + if hour_of_day >= 24 { + return None; + } + if hour_of_day >= 22 { + return Some(0); + } + Some(5) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn raw_value() { + // TODO: Fix this test. How do you get the value contained in the + // Option? + let ice_creams = maybe_ice_cream(12).unwrap(); + + assert_eq!(ice_creams, 5); // Don't change this line. + } + + #[test] + fn check_ice_cream() { + assert_eq!(maybe_ice_cream(0), Some(5)); + assert_eq!(maybe_ice_cream(9), Some(5)); + assert_eq!(maybe_ice_cream(18), Some(5)); + assert_eq!(maybe_ice_cream(22), Some(0)); + assert_eq!(maybe_ice_cream(23), Some(0)); + assert_eq!(maybe_ice_cream(24), None); + assert_eq!(maybe_ice_cream(25), None); + } +} diff --git a/rust/rustlings/exercises/12_options/options2.rs b/rust/rustlings/exercises/12_options/options2.rs new file mode 100644 index 0000000..1039d61 --- /dev/null +++ b/rust/rustlings/exercises/12_options/options2.rs @@ -0,0 +1,39 @@ +fn main() { + // You can optionally experiment here. +} + +#[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`. + if let Some(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 { + optional_integers.push(Some(i)); + } + + let mut cursor = range; + + // TODO: Make this a while-let statement. Remember that `Vec::pop()` + // adds another layer of `Option`. You can do nested pattern matching + // in if-let and while-let statements. + while let Some(Some(integer)) = optional_integers.pop() { + assert_eq!(integer, cursor); + cursor -= 1; + } + + assert_eq!(cursor, 0); + } +} diff --git a/rust/rustlings/exercises/12_options/options3.rs b/rust/rustlings/exercises/12_options/options3.rs new file mode 100644 index 0000000..aecb7a5 --- /dev/null +++ b/rust/rustlings/exercises/12_options/options3.rs @@ -0,0 +1,17 @@ +#[derive(Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let optional_point = Some(Point { x: 100, y: 200 }); + + // TODO: Fix the compiler error by adding something to this match statement. + match optional_point { + Some(ref p) => println!("Coordinates are {},{}", p.x, p.y), + _ => panic!("No match!"), + } + + println!("{optional_point:?}"); // Don't change this line. +} diff --git a/rust/rustlings/exercises/13_error_handling/README.md b/rust/rustlings/exercises/13_error_handling/README.md new file mode 100644 index 0000000..9b6674b --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/13_error_handling/errors1.rs b/rust/rustlings/exercises/13_error_handling/errors1.rs new file mode 100644 index 0000000..b9b9bd5 --- /dev/null +++ b/rust/rustlings/exercises/13_error_handling/errors1.rs @@ -0,0 +1,40 @@ +// TODO: 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 returning `None`. Thankfully, Rust has a similar +// construct to `Option` that can be used to express error conditions. Change +// the function signature and body to return `Result` instead +// of `Option`. +fn generate_nametag_text(name: String) -> Result { + if name.is_empty() { + Err(String::from("Empty names aren't allowed")) + } else { + Ok(format!("Hi! My name is {name}")) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generates_nametag_text_for_a_nonempty_name() { + assert_eq!( + generate_nametag_text("Beyoncé".to_string()).as_deref(), + Ok("Hi! My name is Beyoncé"), + ); + } + + #[test] + fn explains_why_generating_nametag_text_fails() { + assert_eq!( + generate_nametag_text(String::new()) + .as_ref() + .map_err(|e| e.as_str()), + Err("Empty names aren't allowed"), + ); + } +} diff --git a/rust/rustlings/exercises/13_error_handling/errors2.rs b/rust/rustlings/exercises/13_error_handling/errors2.rs new file mode 100644 index 0000000..3d850f7 --- /dev/null +++ b/rust/rustlings/exercises/13_error_handling/errors2.rs @@ -0,0 +1,50 @@ +// 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, we get it as a string. They might have +// typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all. 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`. 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! + +use std::num::ParseIntError; + +fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + + // TODO: Handle the error case as described above. + let qty = item_quantity.parse::()?; + + Ok(qty * cost_per_item + processing_fee) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + use std::num::IntErrorKind; + + #[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().kind(), + &IntErrorKind::InvalidDigit, + ); + } +} diff --git a/rust/rustlings/exercises/13_error_handling/errors3.rs b/rust/rustlings/exercises/13_error_handling/errors3.rs new file mode 100644 index 0000000..bf21bbc --- /dev/null +++ b/rust/rustlings/exercises/13_error_handling/errors3.rs @@ -0,0 +1,33 @@ +// 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? + +use std::num::ParseIntError; + +// Don't change this function. +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) +} + +// TODO: Fix the compiler error by changing the signature and body of the +// `main` function. +fn main() -> Result<(), ParseIntError> { + let mut tokens = 100; + let pretend_user_input = "8"; + + // Don't change this line. + 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."); + } + + Ok(()) +} diff --git a/rust/rustlings/exercises/13_error_handling/errors4.rs b/rust/rustlings/exercises/13_error_handling/errors4.rs new file mode 100644 index 0000000..e5f3d39 --- /dev/null +++ b/rust/rustlings/exercises/13_error_handling/errors4.rs @@ -0,0 +1,44 @@ +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + // TODO: This function shouldn't always return an `Ok`. + // Read the tests below to clarify what should be returned. + if value < 0 { + return Err(CreationError::Negative); + } + if value == 0 { + return Err(CreationError::Zero); + } + Ok(Self(value as u64)) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_creation() { + assert_eq!( + PositiveNonzeroInteger::new(10), + Ok(PositiveNonzeroInteger(10)), + ); + assert_eq!( + PositiveNonzeroInteger::new(-10), + Err(CreationError::Negative), + ); + assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); + } +} diff --git a/rust/rustlings/exercises/13_error_handling/errors5.rs b/rust/rustlings/exercises/13_error_handling/errors5.rs new file mode 100644 index 0000000..405f0dc --- /dev/null +++ b/rust/rustlings/exercises/13_error_handling/errors5.rs @@ -0,0 +1,56 @@ +// This exercise is an altered version of the `errors4` exercise. It 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. +// +// 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`. + +use std::error::Error; +use std::fmt; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// This is required so that `CreationError` can implement `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 for CreationError {} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +// TODO: Add the correct return type `Result<(), Box>`. What can we +// use to describe both errors? Is there a trait which both errors implement? +fn main() -> Result<(), Box> { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} diff --git a/rust/rustlings/exercises/13_error_handling/errors6.rs b/rust/rustlings/exercises/13_error_handling/errors6.rs new file mode 100644 index 0000000..353b50b --- /dev/null +++ b/rust/rustlings/exercises/13_error_handling/errors6.rs @@ -0,0 +1,91 @@ +// 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. + +use std::num::ParseIntError; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// A custom error type that we will be using in `PositiveNonzeroInteger::parse`. +#[derive(PartialEq, Debug)] +enum ParsePosNonzeroError { + Creation(CreationError), + ParseInt(ParseIntError), +} + +impl ParsePosNonzeroError { + fn from_creation(err: CreationError) -> Self { + Self::Creation(err) + } + + // TODO: Add another error conversion function here. + fn from_parse_int(err: ParseIntError) -> Self { + Self::ParseInt(err) + } +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(Self(x as u64)), + } + } + + fn parse(s: &str) -> Result { + // TODO: change this to return an appropriate error instead of panicking + // when `parse()` returns an error. + let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parse_int)?; + Self::new(x).map_err(ParsePosNonzeroError::from_creation) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_error() { + assert!(matches!( + PositiveNonzeroInteger::parse("not a number"), + Err(ParsePosNonzeroError::ParseInt(_)), + )); + } + + #[test] + fn test_negative() { + assert_eq!( + PositiveNonzeroInteger::parse("-555"), + Err(ParsePosNonzeroError::Creation(CreationError::Negative)), + ); + } + + #[test] + fn test_zero() { + assert_eq!( + PositiveNonzeroInteger::parse("0"), + Err(ParsePosNonzeroError::Creation(CreationError::Zero)), + ); + } + + #[test] + fn test_positive() { + let x = PositiveNonzeroInteger::new(42).unwrap(); + assert_eq!(x.0, 42); + assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x)); + } +} diff --git a/rust/rustlings/exercises/14_generics/README.md b/rust/rustlings/exercises/14_generics/README.md new file mode 100644 index 0000000..0c8c8cb --- /dev/null +++ b/rust/rustlings/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 some rather involved 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/book/ch10-01-syntax.html) +- [Bounds](https://doc.rust-lang.org/rust-by-example/generics/bounds.html) diff --git a/rust/rustlings/exercises/14_generics/generics1.rs b/rust/rustlings/exercises/14_generics/generics1.rs new file mode 100644 index 0000000..7e5571f --- /dev/null +++ b/rust/rustlings/exercises/14_generics/generics1.rs @@ -0,0 +1,18 @@ +// `Vec` is generic over the type `T`. In most cases, the compiler is able to +// infer `T`, for example after pushing a value with a concrete type to the vector. +// But in this exercise, the compiler needs some help through a type annotation. + +fn main() { + // TODO: Fix the compiler error by annotating the type of the vector + // `Vec`. Choose `T` as some integer type that can be created from + // `u8` and `i8`. + let mut numbers: Vec = Vec::new(); + + // Don't change the lines below. + let n1: u8 = 42; + numbers.push(n1.into()); + let n2: i8 = -1; + numbers.push(n2.into()); + + println!("{numbers:?}"); +} diff --git a/rust/rustlings/exercises/14_generics/generics2.rs b/rust/rustlings/exercises/14_generics/generics2.rs new file mode 100644 index 0000000..ba77625 --- /dev/null +++ b/rust/rustlings/exercises/14_generics/generics2.rs @@ -0,0 +1,31 @@ +// This powerful wrapper provides the ability to store a positive integer value. +// TODO: Rewrite it using a generic so that it supports wrapping ANY type. +struct Wrapper { + value: T, +} + +// TODO: Adapt the struct's implementation to be generic over the wrapped value. +impl Wrapper { + fn new(value: T) -> Self { + Wrapper { value } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/exercises/15_traits/README.md b/rust/rustlings/exercises/15_traits/README.md new file mode 100644 index 0000000..ac87c64 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/15_traits/traits1.rs b/rust/rustlings/exercises/15_traits/traits1.rs new file mode 100644 index 0000000..fad6a50 --- /dev/null +++ b/rust/rustlings/exercises/15_traits/traits1.rs @@ -0,0 +1,33 @@ +// The trait `AppendBar` has only one function which appends "Bar" to any object +// implementing this trait. +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for String { + // TODO: Implement `AppendBar` for the type `String`. + fn append_bar(self) -> Self { + self + "Bar" + } +} + +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(), "FooBar"); + } + + #[test] + fn is_bar_bar() { + assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); + } +} diff --git a/rust/rustlings/exercises/15_traits/traits2.rs b/rust/rustlings/exercises/15_traits/traits2.rs new file mode 100644 index 0000000..5dfc36d --- /dev/null +++ b/rust/rustlings/exercises/15_traits/traits2.rs @@ -0,0 +1,30 @@ +trait AppendBar { + fn append_bar(self) -> Self; +} + +// TODO: Implement the trait `AppendBar` for a vector of strings. +// `append_bar` should push the string "Bar" into the vector. + +impl AppendBar for Vec { + fn append_bar(self) -> Self { + let mut s = self.clone(); + s.push(String::from("Bar")); + s + } +} + +fn main() { + // You can optionally experiment here. +} + +#[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(), "Bar"); + assert_eq!(foo.pop().unwrap(), "Foo"); + } +} diff --git a/rust/rustlings/exercises/15_traits/traits3.rs b/rust/rustlings/exercises/15_traits/traits3.rs new file mode 100644 index 0000000..144ac0a --- /dev/null +++ b/rust/rustlings/exercises/15_traits/traits3.rs @@ -0,0 +1,40 @@ +trait Licensed { + // TODO: Add a default implementation for `licensing_info` so that + // implementors like the two structs below can share that default behavior + // without repeating the function. + // The default license information should be the string "Default license". + fn licensing_info(&self) -> String { + String::from("Default license") + } +} + +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. + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_licensing_info_the_same() { + let licensing_info = "Default license"; + 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/rust/rustlings/exercises/15_traits/traits4.rs b/rust/rustlings/exercises/15_traits/traits4.rs new file mode 100644 index 0000000..b23dcdd --- /dev/null +++ b/rust/rustlings/exercises/15_traits/traits4.rs @@ -0,0 +1,35 @@ +trait Licensed { + fn licensing_info(&self) -> String { + "Default license".to_string() + } +} + +struct SomeSoftware; +struct OtherSoftware; + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +// TODO: Fix the compiler error by only changing the signature of this function. +fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool { + software1.licensing_info() == software2.licensing_info() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compare_license_information() { + assert!(compare_license_types(SomeSoftware, OtherSoftware)); + } + + #[test] + fn compare_license_information_backwards() { + assert!(compare_license_types(OtherSoftware, SomeSoftware)); + } +} diff --git a/rust/rustlings/exercises/15_traits/traits5.rs b/rust/rustlings/exercises/15_traits/traits5.rs new file mode 100644 index 0000000..6548014 --- /dev/null +++ b/rust/rustlings/exercises/15_traits/traits5.rs @@ -0,0 +1,39 @@ +trait SomeTrait { + fn some_function(&self) -> bool { + true + } +} + +trait OtherTrait { + fn other_function(&self) -> bool { + true + } +} + +struct SomeStruct; +impl SomeTrait for SomeStruct {} +impl OtherTrait for SomeStruct {} + +struct OtherStruct; +impl SomeTrait for OtherStruct {} +impl OtherTrait for OtherStruct {} + +// TODO: Fix the compiler error by only changing the signature of this function. +fn some_func(item: T) -> bool { + item.some_function() && item.other_function() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_some_func() { + assert!(some_func(SomeStruct)); + assert!(some_func(OtherStruct)); + } +} diff --git a/rust/rustlings/exercises/16_lifetimes/README.md b/rust/rustlings/exercises/16_lifetimes/README.md new file mode 100644 index 0000000..91373f7 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/16_lifetimes/lifetimes1.rs b/rust/rustlings/exercises/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000..683bd75 --- /dev/null +++ b/rust/rustlings/exercises/16_lifetimes/lifetimes1.rs @@ -0,0 +1,28 @@ +// 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? + +// TODO: Fix the compiler error by updating the function signature. +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_longest() { + assert_eq!(longest("abcd", "123"), "abcd"); + assert_eq!(longest("abc", "1234"), "1234"); + } +} diff --git a/rust/rustlings/exercises/16_lifetimes/lifetimes2.rs b/rust/rustlings/exercises/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000..ebbc99c --- /dev/null +++ b/rust/rustlings/exercises/16_lifetimes/lifetimes2.rs @@ -0,0 +1,20 @@ +// Don't change this function. +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + if x.len() > y.len() { + x + } else { + y + } +} + +fn main() { + // TODO: Fix the compiler error by moving one line. + + let string1 = String::from("long string is long"); + let string2 = String::from("xyz"); + let result; + { + result = longest(&string1, &string2); + } + println!("The longest string is '{result}'"); +} diff --git a/rust/rustlings/exercises/16_lifetimes/lifetimes3.rs b/rust/rustlings/exercises/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000..91e3922 --- /dev/null +++ b/rust/rustlings/exercises/16_lifetimes/lifetimes3.rs @@ -0,0 +1,16 @@ +// Lifetimes are also needed when structs hold references. + +// TODO: Fix the compiler errors about the struct. +struct Book<'a> { + author: &'a str, + title: &'a str, +} + +fn main() { + let book = Book { + author: "George Orwell", + title: "1984", + }; + + println!("{} by {}", book.title, book.author); +} diff --git a/rust/rustlings/exercises/17_tests/README.md b/rust/rustlings/exercises/17_tests/README.md new file mode 100644 index 0000000..27c6818 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/17_tests/tests1.rs b/rust/rustlings/exercises/17_tests/tests1.rs new file mode 100644 index 0000000..7fd7e10 --- /dev/null +++ b/rust/rustlings/exercises/17_tests/tests1.rs @@ -0,0 +1,24 @@ +// Tests are important to ensure that your code does what you think it should +// do. + +fn is_even(n: i64) -> bool { + n % 2 == 0 +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // TODO: Import `is_even`. You can use a wildcard to import everything in + // the outer module. + use super::*; + + #[test] + fn you_can_assert() { + // TODO: Test the function `is_even` with some values. + assert!(is_even(2)); + assert!(!is_even(3)); + } +} diff --git a/rust/rustlings/exercises/17_tests/tests2.rs b/rust/rustlings/exercises/17_tests/tests2.rs new file mode 100644 index 0000000..16bf0fa --- /dev/null +++ b/rust/rustlings/exercises/17_tests/tests2.rs @@ -0,0 +1,23 @@ +// Calculates the power of 2 using a bit shift. +// `1 << n` is equivalent to "2 to the power of n". +fn power_of_2(n: u8) -> u64 { + 1 << n +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn you_can_assert_eq() { + // TODO: Test the function `power_of_2` with some values. + assert_eq!(power_of_2(1), 2); + assert_eq!(power_of_2(2), 4); + assert_eq!(power_of_2(3), 8); + assert_eq!(power_of_2(4), 16); + } +} diff --git a/rust/rustlings/exercises/17_tests/tests3.rs b/rust/rustlings/exercises/17_tests/tests3.rs new file mode 100644 index 0000000..085bb62 --- /dev/null +++ b/rust/rustlings/exercises/17_tests/tests3.rs @@ -0,0 +1,51 @@ +struct Rectangle { + width: i32, + height: i32, +} + +impl Rectangle { + // Don't change this function. + fn new(width: i32, height: i32) -> Self { + if width <= 0 || height <= 0 { + // Returning a `Result` would be better here. But we want to learn + // how to test functions that can panic. + panic!("Rectangle width and height must be positive"); + } + + Rectangle { width, height } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correct_width_and_height() { + // TODO: This test should check if the rectangle has the size that we + // pass to its constructor. + let rect = Rectangle::new(10, 20); + assert_eq!(rect.width, 10); // Check width + assert_eq!(rect.height, 20); // Check height + } + + // TODO: This test should check if the program panics when we try to create + // a rectangle with negative width. + #[test] + #[should_panic] + fn negative_width() { + let _rect = Rectangle::new(-10, 10); + } + + // TODO: This test should check if the program panics when we try to create + // a rectangle with negative height. + #[test] + #[should_panic] + fn negative_height() { + let _rect = Rectangle::new(10, -10); + } +} diff --git a/rust/rustlings/exercises/18_iterators/README.md b/rust/rustlings/exercises/18_iterators/README.md new file mode 100644 index 0000000..0e8b671 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/18_iterators/iterators1.rs b/rust/rustlings/exercises/18_iterators/iterators1.rs new file mode 100644 index 0000000..71d8112 --- /dev/null +++ b/rust/rustlings/exercises/18_iterators/iterators1.rs @@ -0,0 +1,25 @@ +// 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. + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn iterators() { + let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"]; + + // TODO: Create an iterator over the array. + let mut fav_fruits_iterator = my_fav_fruits.iter(); + + assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); + assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); + assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); + assert_eq!(fav_fruits_iterator.next(), None); // TODO: Replace `todo!()` + } +} diff --git a/rust/rustlings/exercises/18_iterators/iterators2.rs b/rust/rustlings/exercises/18_iterators/iterators2.rs new file mode 100644 index 0000000..c827529 --- /dev/null +++ b/rust/rustlings/exercises/18_iterators/iterators2.rs @@ -0,0 +1,63 @@ +// In this exercise, you'll learn some of the unique advantages that iterators +// can offer. + +// TODO: Complete the `capitalize_first` function. +// "hello" -> "Hello" +fn capitalize_first(input: &str) -> String { + let mut chars = input.chars(); + match chars.next() { + None => String::new(), + Some(first) => first.to_uppercase().to_string() + &input[1..], + } +} + +// TODO: Apply the `capitalize_first` function to a slice of string slices. +// Return a vector of strings. +// ["hello", "world"] -> ["Hello", "World"] +fn capitalize_words_vector(words: &[&str]) -> Vec { + let mut v = Vec::new(); + for word in words { + if !word.trim().is_empty() { + v.push(capitalize_first(word)); + } + } + v +} + +// TODO: Apply the `capitalize_first` function again to a slice of string +// slices. Return a single string. +// ["hello", " ", "world"] -> "Hello World" +fn capitalize_words_string(words: &[&str]) -> String { + capitalize_words_vector(words).join(" ") +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/exercises/18_iterators/iterators3.rs b/rust/rustlings/exercises/18_iterators/iterators3.rs new file mode 100644 index 0000000..919739b --- /dev/null +++ b/rust/rustlings/exercises/18_iterators/iterators3.rs @@ -0,0 +1,84 @@ +#[derive(Debug, PartialEq, Eq)] +enum DivisionError { + // Example: 42 / 0 + DivideByZero, + // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1` + IntegerOverflow, + // Example: 5 / 2 = 2.5 + NotDivisible, +} + +// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`. +// Otherwise, return a suitable error. +fn divide(a: i64, b: i64) -> Result { + if b == 0 { + return Err(DivisionError::DivideByZero); + } + if a == i64::MIN && b == -1 { + return Err(DivisionError::IntegerOverflow); + } + if a % b != 0 { + return Err(DivisionError::NotDivisible); + } + Ok(a / b) +} + +// TODO: Add the correct return type and complete the function body. +// Desired output: `Ok([1, 11, 1426, 3])` +fn result_with_list() -> Result, DivisionError> { + let numbers = [27, 297, 38502, 81]; + numbers.into_iter().map(|n| divide(n, 27)).collect() +} + +// TODO: Add the correct return type and complete the function body. +// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]` +fn list_of_results() -> Vec> { + let numbers = [27, 297, 38502, 81]; + numbers.into_iter().map(|n| divide(n, 27)).collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + assert_eq!(divide(81, -1), Ok(-81)); + assert_eq!(divide(i64::MIN, i64::MIN), Ok(1)); + } + + #[test] + fn test_divide_by_0() { + assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); + } + + #[test] + fn test_integer_overflow() { + assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow)); + } + + #[test] + fn test_not_divisible() { + assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); + } + + #[test] + fn test_divide_0_by_something() { + assert_eq!(divide(0, 81), Ok(0)); + } + + #[test] + fn test_result_with_list() { + assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]); + } + + #[test] + fn test_list_of_results() { + assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]); + } +} diff --git a/rust/rustlings/exercises/18_iterators/iterators4.rs b/rust/rustlings/exercises/18_iterators/iterators4.rs new file mode 100644 index 0000000..f153786 --- /dev/null +++ b/rust/rustlings/exercises/18_iterators/iterators4.rs @@ -0,0 +1,42 @@ +fn factorial(num: u64) -> u64 { + // TODO: Complete this function to return the factorial of `num` which is + // defined as `1 * 2 * 3 * … * num`. + // https://en.wikipedia.org/wiki/Factorial + // + // Do not use: + // - early returns (using the `return` keyword explicitly) + // Try not to use: + // - imperative style loops (for/while) + // - additional variables + // For an extra challenge, don't use: + // - recursion + (1..=num).reduce(|a, b| a * b).unwrap_or(1) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factorial_of_0() { + assert_eq!(factorial(0), 1); + } + + #[test] + fn factorial_of_1() { + assert_eq!(factorial(1), 1); + } + #[test] + fn factorial_of_2() { + assert_eq!(factorial(2), 2); + } + + #[test] + fn factorial_of_4() { + assert_eq!(factorial(4), 24); + } +} diff --git a/rust/rustlings/exercises/18_iterators/iterators5.rs b/rust/rustlings/exercises/18_iterators/iterators5.rs new file mode 100644 index 0000000..74f1c74 --- /dev/null +++ b/rust/rustlings/exercises/18_iterators/iterators5.rs @@ -0,0 +1,155 @@ +// 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 to not use imperative loops (for/while). + +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 +} + +// TODO: Implement the functionality of `count_for` but with an iterator instead +// of a `for` loop. +fn count_iterator(map: &HashMap, value: Progress) -> usize { + map.values().filter(|&&x| x == value).count() + // `map` is a hash map with `String` keys and `Progress` values. + // map = { "variables1": Complete, "from_str": None, … } +} + +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 +} + +// TODO: Implement the functionality of `count_collection_for` but with an +// iterator instead of a `for` loop. +fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { + collection.iter().map(|m| count_iterator(m, value)).sum() + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + 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] + } + + #[test] + fn count_complete() { + let map = get_map(); + assert_eq!(count_iterator(&map, Progress::Complete), 3); + } + + #[test] + fn count_some() { + let map = get_map(); + assert_eq!(count_iterator(&map, Progress::Some), 1); + } + + #[test] + fn count_none() { + let map = get_map(); + assert_eq!(count_iterator(&map, Progress::None), 2); + } + + #[test] + fn count_complete_equals_for() { + let map = get_map(); + let progress_states = [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!( + count_collection_iterator(&collection, Progress::Complete), + 6, + ); + } + + #[test] + fn count_collection_some() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Progress::Some), 1); + } + + #[test] + fn count_collection_none() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Progress::None), 4); + } + + #[test] + fn count_collection_equals_for() { + let collection = get_vec_map(); + let progress_states = [Progress::Complete, Progress::Some, Progress::None]; + + for progress_state in progress_states { + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator(&collection, progress_state), + ); + } + } +} diff --git a/rust/rustlings/exercises/19_smart_pointers/README.md b/rust/rustlings/exercises/19_smart_pointers/README.md new file mode 100644 index 0000000..d56d2b6 --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/19_smart_pointers/arc1.rs b/rust/rustlings/exercises/19_smart_pointers/arc1.rs new file mode 100644 index 0000000..f44e4e1 --- /dev/null +++ b/rust/rustlings/exercises/19_smart_pointers/arc1.rs @@ -0,0 +1,45 @@ +// In this exercise, we are given a `Vec` of `u32` called `numbers` with values +// ranging from 0 to 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, … +// +// Each thread should own a reference-counting pointer to the vector of +// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`. +// +// Don't get distracted by how threads are spawned and joined. We will practice +// that later in the exercises about threads. + +// Don't change the lines below. +#![forbid(unused_imports)] +use std::{sync::Arc, thread}; + +fn main() { + let numbers: Vec<_> = (0..100u32).collect(); + + // TODO: Define `shared_numbers` by using `Arc`. + let shared_numbers = Arc::new(numbers); + + let mut join_handles = Vec::new(); + + for offset in 0..8 { + // TODO: Define `child_numbers` using `shared_numbers`. + let child_numbers = shared_numbers.clone(); + + let handle = thread::spawn(move || { + let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); + println!("Sum of offset {offset} is {sum}"); + }); + + join_handles.push(handle); + } + + for handle in join_handles.into_iter() { + handle.join().unwrap(); + } +} diff --git a/rust/rustlings/exercises/19_smart_pointers/box1.rs b/rust/rustlings/exercises/19_smart_pointers/box1.rs new file mode 100644 index 0000000..ee379ca --- /dev/null +++ b/rust/rustlings/exercises/19_smart_pointers/box1.rs @@ -0,0 +1,50 @@ +// 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`. + +// TODO: Use a `Box` in the enum definition to make the code compile. +#[derive(PartialEq, Debug)] +enum List { + Cons(i32, Box), + Nil, +} + +// TODO: Create an empty cons list. +fn create_empty_list() -> List { + List::Nil +} + +// TODO: Create a non-empty cons list. +fn create_non_empty_list() -> List { + List::Cons(1, Box::new(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(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_empty_list() { + assert_eq!(create_empty_list(), List::Nil); + } + + #[test] + fn test_create_non_empty_list() { + assert_ne!(create_empty_list(), create_non_empty_list()); + } +} diff --git a/rust/rustlings/exercises/19_smart_pointers/cow1.rs b/rust/rustlings/exercises/19_smart_pointers/cow1.rs new file mode 100644 index 0000000..56a25b9 --- /dev/null +++ b/rust/rustlings/exercises/19_smart_pointers/cow1.rs @@ -0,0 +1,66 @@ +// This exercise explores the `Cow` (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. + +use std::borrow::Cow; + +fn abs_all(input: &mut Cow<[i32]>) { + for ind in 0..input.len() { + let value = input[ind]; + if value < 0 { + // Clones into a vector if not already owned. + input.to_mut()[ind] = -value; + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reference_mutation() { + // Clone occurs because `input` needs to be mutated. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + } + + #[test] + fn reference_no_mutation() { + // No clone occurs because `input` doesn't need to be mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Borrowed(_))); + } + + #[test] + fn owned_no_mutation() { + // We can also pass `vec` without `&` so `Cow` owns it directly. In this + // case, no mutation occurs (all numbers are already absolute) and thus + // also no clone. But the result is still owned because it was never + // borrowed or mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + } + + #[test] + fn owned_mutation() { + // Of course this is also the case if a mutation does occur (not all + // numbers are absolute). In this case, the call to `to_mut()` in the + // `abs_all` function returns a reference to the same data as before. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + } +} diff --git a/rust/rustlings/exercises/19_smart_pointers/rc1.rs b/rust/rustlings/exercises/19_smart_pointers/rc1.rs new file mode 100644 index 0000000..5c9ce84 --- /dev/null +++ b/rust/rustlings/exercises/19_smart_pointers/rc1.rs @@ -0,0 +1,108 @@ +// 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 `Planet`s. The planets take ownership of the sun, indicating that +// they revolve around the sun. + +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:?}!"); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rc1() { + 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::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + // TODO + let uranus = Planet::Uranus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + // TODO + let neptune = Planet::Neptune(Rc::clone(&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 + drop(earth); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + + // TODO + drop(venus); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + + // TODO + drop(mercury); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + assert_eq!(Rc::strong_count(&sun), 1); + } +} diff --git a/rust/rustlings/exercises/20_threads/README.md b/rust/rustlings/exercises/20_threads/README.md new file mode 100644 index 0000000..0b32fb1 --- /dev/null +++ b/rust/rustlings/exercises/20_threads/README.md @@ -0,0 +1,10 @@ +# 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) +- [Using Message Passing to Transfer Data Between Threads](https://doc.rust-lang.org/book/ch16-02-message-passing.html) diff --git a/rust/rustlings/exercises/20_threads/threads1.rs b/rust/rustlings/exercises/20_threads/threads1.rs new file mode 100644 index 0000000..dbc64b1 --- /dev/null +++ b/rust/rustlings/exercises/20_threads/threads1.rs @@ -0,0 +1,37 @@ +// This program spawns multiple threads that each runs for at least 250ms, and +// each thread returns how much time it took to complete. The program should +// wait until all the spawned threads have finished and should collect their +// return values into a vector. + +use std::{ + thread, + time::{Duration, Instant}, +}; + +fn main() { + let mut handles = Vec::new(); + for i in 0..10 { + let handle = thread::spawn(move || { + let start = Instant::now(); + thread::sleep(Duration::from_millis(250)); + println!("Thread {i} done"); + start.elapsed().as_millis() + }); + handles.push(handle); + } + + let mut results = Vec::new(); + for handle in handles { + // TODO: Collect the results of all threads into the `results` vector. + // Use the `JoinHandle` struct which is returned by `thread::spawn`. + } + + if results.len() != 10 { + panic!("Oh no! Some thread isn't done yet!"); + } + + println!(); + for (i, result) in results.into_iter().enumerate() { + println!("Thread {i} took {result}ms"); + } +} diff --git a/rust/rustlings/exercises/20_threads/threads2.rs b/rust/rustlings/exercises/20_threads/threads2.rs new file mode 100644 index 0000000..7020cb9 --- /dev/null +++ b/rust/rustlings/exercises/20_threads/threads2.rs @@ -0,0 +1,34 @@ +// 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_done` + +use std::{sync::Arc, thread, time::Duration}; + +struct JobStatus { + jobs_done: u32, +} + +fn main() { + // TODO: `Arc` isn't enough if you want a **mutable** shared state. + let status = Arc::new(JobStatus { jobs_done: 0 }); + + let mut handles = Vec::new(); + 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_done += 1; + }); + handles.push(handle); + } + + // Waiting for all jobs to complete. + for handle in handles { + handle.join().unwrap(); + } + + // TODO: Print the value of `JobStatus.jobs_done`. + println!("Jobs done: {}", todo!()); +} diff --git a/rust/rustlings/exercises/20_threads/threads3.rs b/rust/rustlings/exercises/20_threads/threads3.rs new file mode 100644 index 0000000..6d16bd9 --- /dev/null +++ b/rust/rustlings/exercises/20_threads/threads3.rs @@ -0,0 +1,60 @@ +use std::{sync::mpsc, thread, time::Duration}; + +struct Queue { + first_half: Vec, + second_half: Vec, +} + +impl Queue { + fn new() -> Self { + Self { + first_half: vec![1, 2, 3, 4, 5], + second_half: vec![6, 7, 8, 9, 10], + } + } +} + +fn send_tx(q: Queue, tx: mpsc::Sender) { + // TODO: We want to send `tx` to both threads. But currently, it is moved + // into the first thread. How could you solve this problem? + thread::spawn(move || { + for val in q.first_half { + println!("Sending {val:?}"); + tx.send(val).unwrap(); + thread::sleep(Duration::from_millis(250)); + } + }); + + thread::spawn(move || { + for val in q.second_half { + println!("Sending {val:?}"); + tx.send(val).unwrap(); + thread::sleep(Duration::from_millis(250)); + } + }); +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn threads3() { + let (tx, rx) = mpsc::channel(); + let queue = Queue::new(); + + send_tx(queue, tx); + + let mut received = Vec::with_capacity(10); + for value in rx { + received.push(value); + } + + received.sort(); + assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + } +} diff --git a/rust/rustlings/exercises/21_macros/README.md b/rust/rustlings/exercises/21_macros/README.md new file mode 100644 index 0000000..de7fb7b --- /dev/null +++ b/rust/rustlings/exercises/21_macros/README.md @@ -0,0 +1,15 @@ +# 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 + +- [The Rust Book - Macros](https://doc.rust-lang.org/book/ch20-05-macros.html) +- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) +- [Rust by Example - macro_rules!](https://doc.rust-lang.org/rust-by-example/macros.html) diff --git a/rust/rustlings/exercises/21_macros/macros1.rs b/rust/rustlings/exercises/21_macros/macros1.rs new file mode 100644 index 0000000..fb3c3ff --- /dev/null +++ b/rust/rustlings/exercises/21_macros/macros1.rs @@ -0,0 +1,10 @@ +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; +} + +fn main() { + // TODO: Fix the macro call. + my_macro(); +} diff --git a/rust/rustlings/exercises/21_macros/macros2.rs b/rust/rustlings/exercises/21_macros/macros2.rs new file mode 100644 index 0000000..2d9dec7 --- /dev/null +++ b/rust/rustlings/exercises/21_macros/macros2.rs @@ -0,0 +1,10 @@ +fn main() { + my_macro!(); +} + +// TODO: Fix the compiler error by moving the whole definition of this macro. +macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; +} diff --git a/rust/rustlings/exercises/21_macros/macros3.rs b/rust/rustlings/exercises/21_macros/macros3.rs new file mode 100644 index 0000000..9537494 --- /dev/null +++ b/rust/rustlings/exercises/21_macros/macros3.rs @@ -0,0 +1,13 @@ +// TODO: Fix the compiler error without taking the macro definition out of this +// module. +mod macros { + macro_rules! my_macro { + () => { + println!("Check out my macro!"); + }; + } +} + +fn main() { + my_macro!(); +} diff --git a/rust/rustlings/exercises/21_macros/macros4.rs b/rust/rustlings/exercises/21_macros/macros4.rs new file mode 100644 index 0000000..9d77f6a --- /dev/null +++ b/rust/rustlings/exercises/21_macros/macros4.rs @@ -0,0 +1,15 @@ +// TODO: Fix the compiler error by adding one or two characters. +#[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/rust/rustlings/exercises/22_clippy/README.md b/rust/rustlings/exercises/22_clippy/README.md new file mode 100644 index 0000000..55438af --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/22_clippy/clippy1.rs b/rust/rustlings/exercises/22_clippy/clippy1.rs new file mode 100644 index 0000000..7165da4 --- /dev/null +++ b/rust/rustlings/exercises/22_clippy/clippy1.rs @@ -0,0 +1,15 @@ +// 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. + +fn main() { + // TODO: Fix the Clippy lint in this line. + let pi = 3.14; + let radius: f32 = 5.0; + + let area = pi * radius.powi(2); + + println!("The area of a circle with radius {radius:.2} is {area:.5}"); +} diff --git a/rust/rustlings/exercises/22_clippy/clippy2.rs b/rust/rustlings/exercises/22_clippy/clippy2.rs new file mode 100644 index 0000000..8cfe6f8 --- /dev/null +++ b/rust/rustlings/exercises/22_clippy/clippy2.rs @@ -0,0 +1,10 @@ +fn main() { + let mut res = 42; + let option = Some(12); + // TODO: Fix the Clippy lint. + for x in option { + res += x; + } + + println!("{res}"); +} diff --git a/rust/rustlings/exercises/22_clippy/clippy3.rs b/rust/rustlings/exercises/22_clippy/clippy3.rs new file mode 100644 index 0000000..7a3cb39 --- /dev/null +++ b/rust/rustlings/exercises/22_clippy/clippy3.rs @@ -0,0 +1,29 @@ +// Here are some more easy Clippy fixes so you can see its utility 📎 +// TODO: Fix all the Clippy lints. + +#[rustfmt::skip] +#[allow(unused_variables, unused_assignments)] +fn main() { + let my_option: Option<&str> = None; + // Assume that you don't know the value of `my_option`. + // In the case of `Some`, we want to print its value. + if my_option.is_none() { + println!("{}", 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_a}; value b: {value_b}"); +} diff --git a/rust/rustlings/exercises/23_conversions/README.md b/rust/rustlings/exercises/23_conversions/README.md new file mode 100644 index 0000000..619a78c --- /dev/null +++ b/rust/rustlings/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/rust/rustlings/exercises/23_conversions/as_ref_mut.rs b/rust/rustlings/exercises/23_conversions/as_ref_mut.rs new file mode 100644 index 0000000..d7892dd --- /dev/null +++ b/rust/rustlings/exercises/23_conversions/as_ref_mut.rs @@ -0,0 +1,62 @@ +// 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. + +// Obtain the number of bytes (not characters) in the given argument +// (`.len()` returns the number of bytes in a string). +// TODO: Add the `AsRef` trait appropriately as a trait bound. +fn byte_counter(arg: T) -> usize { + arg.as_ref().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. +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/exercises/23_conversions/from_into.rs b/rust/rustlings/exercises/23_conversions/from_into.rs new file mode 100644 index 0000000..bc2783a --- /dev/null +++ b/rust/rustlings/exercises/23_conversions/from_into.rs @@ -0,0 +1,130 @@ +// The `From` trait is used for value-to-value conversions. If `From` is +// implemented, an implementation of `Into` is automatically provided. +// You can read more about it in the documentation: +// https://doc.rust-lang.org/std/convert/trait.From.html + +#[derive(Debug)] +struct Person { + name: String, + age: u8, +} + +// 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() -> Self { + Self { + name: String::from("John"), + age: 30, + } + } +} + +// TODO: Complete this `From` implementation to be able to parse a `Person` +// out of a string in the form of "Mark,20". +// Note that you'll need to parse the age component into a `u8` with something +// like `"4".parse::()`. +// +// Steps: +// 1. Split the given string on the commas present in it. +// 2. If the split operation returns less or more than 2 elements, return the +// default of `Person`. +// 3. Use the first element from the split operation as the name. +// 4. If the name is empty, return the default of `Person`. +// 5. Parse the second element from the split operation into a `u8` as the age. +// 6. If parsing the age fails, return the default of `Person`. +impl From<&str> for Person { + fn from(s: &str) -> Self {} +} + +fn main() { + // Use the `from` function. + let p1 = Person::from("Mark,20"); + println!("{p1:?}"); + + // Since `From` is implemented for Person, we are able to use `Into`. + let p2: Person = "Gerald,70".into(); + println!("{p2:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_default() { + let dp = Person::default(); + assert_eq!(dp.name, "John"); + assert_eq!(dp.age, 30); + } + + #[test] + fn test_bad_convert() { + let p = Person::from(""); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_good_convert() { + let p = Person::from("Mark,20"); + assert_eq!(p.name, "Mark"); + assert_eq!(p.age, 20); + } + + #[test] + fn test_bad_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, "John"); + assert_eq!(p.age, 30); + } + + #[test] + fn test_trailing_comma_and_some_string() { + let p: Person = Person::from("Mike,32,dog"); + assert_eq!(p.name, "John"); + assert_eq!(p.age, 30); + } +} diff --git a/rust/rustlings/exercises/23_conversions/from_str.rs b/rust/rustlings/exercises/23_conversions/from_str.rs new file mode 100644 index 0000000..ec6d3fd --- /dev/null +++ b/rust/rustlings/exercises/23_conversions/from_str.rs @@ -0,0 +1,113 @@ +// This is similar to the previous `from_into` exercise. 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 in the documentation: +// https://doc.rust-lang.org/std/str/trait.FromStr.html + +use std::num::ParseIntError; +use std::str::FromStr; + +#[derive(Debug, PartialEq)] +struct Person { + name: String, + age: u8, +} + +// We will use this error type for the `FromStr` implementation. +#[derive(Debug, PartialEq)] +enum ParsePersonError { + // Incorrect number of fields + BadLen, + // Empty name field + NoName, + // Wrapped error from parse::() + ParseInt(ParseIntError), +} + +// TODO: Complete this `FromStr` implementation to be able to parse a `Person` +// out of a string in the form of "Mark,20". +// Note that you'll need to parse the age component into a `u8` with something +// like `"4".parse::()`. +// +// Steps: +// 1. Split the given string on the commas present in it. +// 2. If the split operation returns less or more than 2 elements, return the +// error `ParsePersonError::BadLen`. +// 3. Use the first element from the split operation as the name. +// 4. If the name is empty, return the error `ParsePersonError::NoName`. +// 5. Parse the second element from the split operation into a `u8` as the age. +// 6. If parsing the age fails, return the error `ParsePersonError::ParseInt`. +impl FromStr for Person { + type Err = ParsePersonError; + + fn from_str(s: &str) -> Result {} +} + +fn main() { + let p = "Mark,20".parse::(); + println!("{p:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + use ParsePersonError::*; + + #[test] + fn empty_input() { + assert_eq!("".parse::(), Err(BadLen)); + } + + #[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(ParseInt(_)))); + } + + #[test] + fn invalid_age() { + assert!(matches!("John,twenty".parse::(), Err(ParseInt(_)))); + } + + #[test] + fn missing_comma_and_age() { + assert_eq!("John".parse::(), Err(BadLen)); + } + + #[test] + fn missing_name() { + assert_eq!(",1".parse::(), Err(NoName)); + } + + #[test] + fn missing_name_and_age() { + assert!(matches!(",".parse::(), Err(NoName | ParseInt(_)))); + } + + #[test] + fn missing_name_and_invalid_age() { + assert!(matches!( + ",one".parse::(), + Err(NoName | ParseInt(_)), + )); + } + + #[test] + fn trailing_comma() { + assert_eq!("John,32,".parse::(), Err(BadLen)); + } + + #[test] + fn trailing_comma_and_some_string() { + assert_eq!("John,32,man".parse::(), Err(BadLen)); + } +} diff --git a/rust/rustlings/exercises/23_conversions/try_from_into.rs b/rust/rustlings/exercises/23_conversions/try_from_into.rs new file mode 100644 index 0000000..f3ae80a --- /dev/null +++ b/rust/rustlings/exercises/23_conversions/try_from_into.rs @@ -0,0 +1,177 @@ +// `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 in the documentation: +// https://doc.rust-lang.org/std/convert/trait.TryFrom.html + +#![allow(clippy::useless_vec)] +use std::convert::{TryFrom, TryInto}; + +#[derive(Debug, PartialEq)] +struct Color { + red: u8, + green: u8, + blue: u8, +} + +// We will use this error type for the `TryFrom` conversions. +#[derive(Debug, PartialEq)] +enum IntoColorError { + // Incorrect length of slice + BadLen, + // Integer conversion error + IntConversion, +} + +// TODO: Tuple implementation. +// Correct RGB color values must be integers in the 0..=255 range. +impl TryFrom<(i16, i16, i16)> for Color { + type Error = IntoColorError; + + fn try_from(tuple: (i16, i16, i16)) -> Result {} +} + +// TODO: Array implementation. +impl TryFrom<[i16; 3]> for Color { + type Error = IntoColorError; + + fn try_from(arr: [i16; 3]) -> Result {} +} + +// TODO: Slice implementation. +// This implementation needs to check the slice length. +impl TryFrom<&[i16]> for Color { + type Error = IntoColorError; + + fn try_from(slice: &[i16]) -> Result {} +} + +fn main() { + // Using the `try_from` function. + let c1 = Color::try_from((183, 65, 14)); + println!("{c1:?}"); + + // Since `TryFrom` is implemented for `Color`, we can use `TryInto`. + let c2: Result = [183, 65, 14].try_into(); + println!("{c2:?}"); + + let v = vec![183, 65, 14]; + // With slice we should use the `try_from` function + let c3 = Color::try_from(&v[..]); + println!("{c3:?}"); + // or put the slice within round brackets and use `try_into`. + let c4: Result = (&v[..]).try_into(); + println!("{c4:?}"); +} + +#[cfg(test)] +mod tests { + use super::*; + use IntoColorError::*; + + #[test] + fn test_tuple_out_of_range_positive() { + assert_eq!(Color::try_from((256, 1000, 10000)), Err(IntConversion)); + } + + #[test] + fn test_tuple_out_of_range_negative() { + assert_eq!(Color::try_from((-1, -10, -256)), Err(IntConversion)); + } + + #[test] + fn test_tuple_sum() { + assert_eq!(Color::try_from((-1, 255, 255)), Err(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(IntConversion)); + } + + #[test] + fn test_array_out_of_range_negative() { + let c: Result = [-10, -256, -1].try_into(); + assert_eq!(c, Err(IntConversion)); + } + + #[test] + fn test_array_sum() { + let c: Result = [-1, 255, 255].try_into(); + assert_eq!(c, Err(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(IntConversion)); + } + + #[test] + fn test_slice_out_of_range_negative() { + let arr = [-256, -1, -10]; + assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); + } + + #[test] + fn test_slice_sum() { + let arr = [-1, 255, 255]; + assert_eq!(Color::try_from(&arr[..]), Err(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(BadLen)); + } + + #[test] + fn test_slice_insufficient_length() { + let v = vec![0, 0]; + assert_eq!(Color::try_from(&v[..]), Err(BadLen)); + } +} diff --git a/rust/rustlings/exercises/23_conversions/using_as.rs b/rust/rustlings/exercises/23_conversions/using_as.rs new file mode 100644 index 0000000..c131d1f --- /dev/null +++ b/rust/rustlings/exercises/23_conversions/using_as.rs @@ -0,0 +1,24 @@ +// Type casting in Rust is done via the usage of the `as` operator. +// Note that the `as` operator is not only used when type casting. It also helps +// with renaming imports. + +fn average(values: &[f64]) -> f64 { + let total = values.iter().sum::(); + // TODO: Make a conversion before dividing. + 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/rust/rustlings/exercises/README.md b/rust/rustlings/exercises/README.md new file mode 100644 index 0000000..1df5cc3 --- /dev/null +++ b/rust/rustlings/exercises/README.md @@ -0,0 +1,27 @@ +# Exercise to Book Chapter mapping + +| Exercise | Book Chapter | +| ---------------------- | ------------------- | +| variables | §3.1 | +| functions | §3.3 | +| if | §3.5 | +| primitive_types | §3.2, §4.3 | +| vecs | §8.1 | +| move_semantics | §4.1-2 | +| structs | §5.1, §5.3 | +| enums | §6, §18.3 | +| strings | §8.2 | +| modules | §7 | +| hashmaps | §8.3 | +| options | §10.1 | +| error_handling | §9 | +| generics | §10 | +| traits | §10.2 | +| lifetimes | §10.3 | +| tests | §11.1 | +| iterators | §13.2-4 | +| smart_pointers | §15, §16.3 | +| threads | §16.1-3 | +| macros | §20.5 | +| clippy | Appendix D | +| conversions | n/a | diff --git a/rust/rustlings/exercises/quizzes/README.md b/rust/rustlings/exercises/quizzes/README.md new file mode 100644 index 0000000..4d3bcd9 --- /dev/null +++ b/rust/rustlings/exercises/quizzes/README.md @@ -0,0 +1,3 @@ +# Quizzes + +After every couple of sections, there will be a quiz in this directory that'll test your knowledge on a bunch of sections at once. diff --git a/rust/rustlings/exercises/quizzes/quiz1.rs b/rust/rustlings/exercises/quizzes/quiz1.rs new file mode 100644 index 0000000..b787d7e --- /dev/null +++ b/rust/rustlings/exercises/quizzes/quiz1.rs @@ -0,0 +1,35 @@ +// This is a quiz for the following sections: +// - Variables +// - Functions +// - If +// +// Mary is buying apples. The price of an apple is calculated as follows: +// - An apple costs 2 rustbucks. +// - However, if Mary buys more than 40 apples, the price of each apple in the +// entire order is reduced to only 1 rustbuck! + +fn calculate_price_of_apples(n: i32) -> i32 { + if n > 40 { + n + } else { + 2 * n + } +} + +fn main() { + // You can optionally experiment here. +} + +// Don't change the tests! +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verify_test() { + assert_eq!(calculate_price_of_apples(35), 70); + assert_eq!(calculate_price_of_apples(40), 80); + assert_eq!(calculate_price_of_apples(41), 41); + assert_eq!(calculate_price_of_apples(65), 65); + } +} diff --git a/rust/rustlings/exercises/quizzes/quiz2.rs b/rust/rustlings/exercises/quizzes/quiz2.rs new file mode 100644 index 0000000..fd32810 --- /dev/null +++ b/rust/rustlings/exercises/quizzes/quiz2.rs @@ -0,0 +1,81 @@ +// This is a quiz for the following sections: +// - Strings +// - Vecs +// - Move semantics +// - Modules +// - Enums +// +// Let's build a little machine in the form of a function. As input, we're going +// to give a list of strings and commands. These commands determine what action +// is going to be applied to the string. It can either be: +// - Uppercase the string +// - Trim the string +// - Append "bar" to the string a specified amount of times +// +// The exact form of this will be: +// - The input is going to be a Vector of 2-length tuples, +// the first element is the string, the second one is the command. +// - The output element is going to be a vector of strings. + +enum Command { + Uppercase, + Trim, + Append(usize), +} + +mod my_module { + use super::Command; + + // TODO: Complete the function as described above. + // pub fn transformer(input: ???) -> ??? { ??? } + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut out = Vec::new(); + for inp in input { + out.push(match inp.1 { + Command::Uppercase => inp.0.to_uppercase(), + Command::Trim => String::from(inp.0.trim()), + Command::Append(n) => { + let mut r = inp.0; + for _ in 0..n { + r += "bar"; + } + r + } + }); + } + out + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // TODO: What do we need to import to have `transformer` in scope? + // use ???; + use super::Command; + use super::my_module::transformer; + + #[test] + fn it_works() { + let input = vec![ + ("hello".to_string(), Command::Uppercase), + (" all roads lead to rome! ".to_string(), Command::Trim), + ("foo".to_string(), Command::Append(1)), + ("bar".to_string(), Command::Append(5)), + ]; + let output = transformer(input); + + assert_eq!( + output, + [ + "HELLO", + "all roads lead to rome!", + "foobar", + "barbarbarbarbarbar", + ] + ); + } +} diff --git a/rust/rustlings/exercises/quizzes/quiz3.rs b/rust/rustlings/exercises/quizzes/quiz3.rs new file mode 100644 index 0000000..5bb859f --- /dev/null +++ b/rust/rustlings/exercises/quizzes/quiz3.rs @@ -0,0 +1,64 @@ +// This quiz tests: +// - Generics +// - Traits +// +// An imaginary magical school has a new report card generation system written +// in Rust! Currently, the system only supports creating report cards where the +// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the +// school also issues alphabetical grades (A+ -> F-) and needs to be able to +// print both types of report card! +// +// Make the necessary code changes in the struct `ReportCard` and the impl +// block to support alphabetical report cards in addition to numerical ones. + +// TODO: Adjust the struct as described above. +struct ReportCard { + grade: T, + student_name: String, + student_age: u8, +} + +// TODO: Adjust the impl block as described above. +impl ReportCard { + fn print(&self) -> String { + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade, + ) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generate_numeric_report_card() { + let report_card = ReportCard { + grade: 2.1, + student_name: "Tom Wriggle".to_string(), + student_age: 12, + }; + assert_eq!( + report_card.print(), + "Tom Wriggle (12) - achieved a grade of 2.1", + ); + } + + #[test] + fn generate_alphabetic_report_card() { + let report_card = ReportCard { + grade: "A+", + student_name: "Gary Plotter".to_string(), + student_age: 11, + }; + assert_eq!( + report_card.print(), + "Gary Plotter (11) - achieved a grade of A+", + ); + } +} diff --git a/rust/rustlings/rust-analyzer.toml b/rust/rustlings/rust-analyzer.toml new file mode 100644 index 0000000..977b6ce --- /dev/null +++ b/rust/rustlings/rust-analyzer.toml @@ -0,0 +1,3 @@ +check.command = "clippy" +check.extraArgs = ["--profile", "test"] +cargo.targetDir = true diff --git a/rust/rustlings/solutions/00_intro/intro1.rs b/rust/rustlings/solutions/00_intro/intro1.rs new file mode 100644 index 0000000..4fe8454 --- /dev/null +++ b/rust/rustlings/solutions/00_intro/intro1.rs @@ -0,0 +1,5 @@ +fn main() { + // Congratulations, you finished the first exercise 🎉 + // As an introduction to Rustlings, the first exercise only required + // entering `n` in the terminal to go to the next exercise. +} diff --git a/rust/rustlings/solutions/00_intro/intro2.rs b/rust/rustlings/solutions/00_intro/intro2.rs new file mode 100644 index 0000000..b8e031a --- /dev/null +++ b/rust/rustlings/solutions/00_intro/intro2.rs @@ -0,0 +1,4 @@ +fn main() { + // `println!` instead of `printline!`. + println!("Hello world!"); +} diff --git a/rust/rustlings/solutions/01_variables/variables1.rs b/rust/rustlings/solutions/01_variables/variables1.rs new file mode 100644 index 0000000..58d046b --- /dev/null +++ b/rust/rustlings/solutions/01_variables/variables1.rs @@ -0,0 +1,6 @@ +fn main() { + // Declaring variables requires the `let` keyword. + let x = 5; + + println!("x has the value {x}"); +} diff --git a/rust/rustlings/solutions/01_variables/variables2.rs b/rust/rustlings/solutions/01_variables/variables2.rs new file mode 100644 index 0000000..50b8d1b --- /dev/null +++ b/rust/rustlings/solutions/01_variables/variables2.rs @@ -0,0 +1,16 @@ +fn main() { + // The easiest way to fix the compiler error is to initialize the + // variable `x`. By setting its value to an integer, Rust infers its type + // as `i32` which is the default type for integers. + let x = 42; + + // But we can enforce a type different from the default `i32` by adding + // a type annotation: + // let x: u8 = 42; + + if x == 10 { + println!("x is ten!"); + } else { + println!("x is not ten!"); + } +} diff --git a/rust/rustlings/solutions/01_variables/variables3.rs b/rust/rustlings/solutions/01_variables/variables3.rs new file mode 100644 index 0000000..15f6557 --- /dev/null +++ b/rust/rustlings/solutions/01_variables/variables3.rs @@ -0,0 +1,15 @@ +#![allow(clippy::needless_late_init)] + +fn main() { + // Reading uninitialized variables isn't allowed in Rust! + // Therefore, we need to assign a value first. + let x: i32 = 42; + + println!("Number {x}"); + + // It is possible to declare a variable and initialize it later. + // But it can't be used before initialization. + let y: i32; + y = 42; + println!("Number {y}"); +} diff --git a/rust/rustlings/solutions/01_variables/variables4.rs b/rust/rustlings/solutions/01_variables/variables4.rs new file mode 100644 index 0000000..7de6bcb --- /dev/null +++ b/rust/rustlings/solutions/01_variables/variables4.rs @@ -0,0 +1,9 @@ +fn main() { + // In Rust, variables are immutable by default. + // Adding the `mut` keyword after `let` makes the declared variable mutable. + let mut x = 3; + println!("Number {x}"); + + x = 5; + println!("Number {x}"); +} diff --git a/rust/rustlings/solutions/01_variables/variables5.rs b/rust/rustlings/solutions/01_variables/variables5.rs new file mode 100644 index 0000000..0ea3903 --- /dev/null +++ b/rust/rustlings/solutions/01_variables/variables5.rs @@ -0,0 +1,9 @@ +fn main() { + let number = "T-H-R-E-E"; + println!("Spell a number: {number}"); + + // Using variable shadowing + // https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing + let number = 3; + println!("Number plus two is: {}", number + 2); +} diff --git a/rust/rustlings/solutions/01_variables/variables6.rs b/rust/rustlings/solutions/01_variables/variables6.rs new file mode 100644 index 0000000..25b7a1e --- /dev/null +++ b/rust/rustlings/solutions/01_variables/variables6.rs @@ -0,0 +1,6 @@ +// The type of constants must always be annotated. +const NUMBER: u64 = 3; + +fn main() { + println!("Number: {NUMBER}"); +} diff --git a/rust/rustlings/solutions/02_functions/functions1.rs b/rust/rustlings/solutions/02_functions/functions1.rs new file mode 100644 index 0000000..dc52744 --- /dev/null +++ b/rust/rustlings/solutions/02_functions/functions1.rs @@ -0,0 +1,8 @@ +// Some function with the name `call_me` without arguments or a return value. +fn call_me() { + println!("Hello world!"); +} + +fn main() { + call_me(); +} diff --git a/rust/rustlings/solutions/02_functions/functions2.rs b/rust/rustlings/solutions/02_functions/functions2.rs new file mode 100644 index 0000000..f14ffa3 --- /dev/null +++ b/rust/rustlings/solutions/02_functions/functions2.rs @@ -0,0 +1,11 @@ +// The type of function arguments must be annotated. +// Added the type annotation `u64`. +fn call_me(num: u64) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + call_me(3); +} diff --git a/rust/rustlings/solutions/02_functions/functions3.rs b/rust/rustlings/solutions/02_functions/functions3.rs new file mode 100644 index 0000000..ce5fe8e --- /dev/null +++ b/rust/rustlings/solutions/02_functions/functions3.rs @@ -0,0 +1,10 @@ +fn call_me(num: u8) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + // `call_me` expects an argument. + call_me(5); +} diff --git a/rust/rustlings/solutions/02_functions/functions4.rs b/rust/rustlings/solutions/02_functions/functions4.rs new file mode 100644 index 0000000..f823de2 --- /dev/null +++ b/rust/rustlings/solutions/02_functions/functions4.rs @@ -0,0 +1,17 @@ +fn is_even(num: i64) -> bool { + num % 2 == 0 +} + +// The return type must always be annotated. +fn sale_price(price: i64) -> i64 { + if is_even(price) { + price - 10 + } else { + price - 3 + } +} + +fn main() { + let original_price = 51; + println!("Your sale price is {}", sale_price(original_price)); +} diff --git a/rust/rustlings/solutions/02_functions/functions5.rs b/rust/rustlings/solutions/02_functions/functions5.rs new file mode 100644 index 0000000..677f327 --- /dev/null +++ b/rust/rustlings/solutions/02_functions/functions5.rs @@ -0,0 +1,9 @@ +fn square(num: i32) -> i32 { + // Removed the semicolon `;` at the end of the line below to implicitly return the result. + num * num +} + +fn main() { + let answer = square(3); + println!("The square of 3 is {answer}"); +} diff --git a/rust/rustlings/solutions/03_if/if1.rs b/rust/rustlings/solutions/03_if/if1.rs new file mode 100644 index 0000000..8512a60 --- /dev/null +++ b/rust/rustlings/solutions/03_if/if1.rs @@ -0,0 +1,28 @@ +fn bigger(a: i32, b: i32) -> i32 { + if a > b { a } else { b } +} + +fn main() { + // You can optionally experiment here. +} + +// 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/rust/rustlings/solutions/03_if/if2.rs b/rust/rustlings/solutions/03_if/if2.rs new file mode 100644 index 0000000..21c0dcd --- /dev/null +++ b/rust/rustlings/solutions/03_if/if2.rs @@ -0,0 +1,35 @@ +fn picky_eater(food: &str) -> &str { + if food == "strawberry" { + "Yummy!" + } else if food == "potato" { + "I guess I can eat that." + } else { + "No thanks!" + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn yummy_food() { + assert_eq!(picky_eater("strawberry"), "Yummy!"); + } + + #[test] + fn neutral_food() { + assert_eq!(picky_eater("potato"), "I guess I can eat that."); + } + + #[test] + fn default_disliked_food() { + assert_eq!(picky_eater("broccoli"), "No thanks!"); + assert_eq!(picky_eater("gummy bears"), "No thanks!"); + assert_eq!(picky_eater("literally anything"), "No thanks!"); + } +} diff --git a/rust/rustlings/solutions/03_if/if3.rs b/rust/rustlings/solutions/03_if/if3.rs new file mode 100644 index 0000000..571644d --- /dev/null +++ b/rust/rustlings/solutions/03_if/if3.rs @@ -0,0 +1,53 @@ +fn animal_habitat(animal: &str) -> &str { + let identifier = if animal == "crab" { + 1 + } else if animal == "gopher" { + 2 + } else if animal == "snake" { + 3 + } else { + // Any unused identifier. + 4 + }; + + // Instead of such an identifier, you would use an enum in Rust. + // But we didn't get into enums yet. + if identifier == 1 { + "Beach" + } else if identifier == 2 { + "Burrow" + } else if identifier == 3 { + "Desert" + } else { + "Unknown" + } +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/solutions/04_primitive_types/primitive_types1.rs b/rust/rustlings/solutions/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000..fac6ec0 --- /dev/null +++ b/rust/rustlings/solutions/04_primitive_types/primitive_types1.rs @@ -0,0 +1,11 @@ +fn main() { + let is_morning = true; + if is_morning { + println!("Good morning!"); + } + + let is_evening = !is_morning; + if is_evening { + println!("Good evening!"); + } +} diff --git a/rust/rustlings/solutions/04_primitive_types/primitive_types2.rs b/rust/rustlings/solutions/04_primitive_types/primitive_types2.rs new file mode 100644 index 0000000..eecc680 --- /dev/null +++ b/rust/rustlings/solutions/04_primitive_types/primitive_types2.rs @@ -0,0 +1,21 @@ +fn main() { + 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!"); + } + + // Example with an emoji. + let your_character = '🦀'; + + if your_character.is_alphabetic() { + println!("Alphabetical!"); + } else if your_character.is_numeric() { + println!("Numerical!"); + } else { + println!("Neither alphabetic nor numeric!"); + } +} diff --git a/rust/rustlings/solutions/04_primitive_types/primitive_types3.rs b/rust/rustlings/solutions/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000..8dd109f --- /dev/null +++ b/rust/rustlings/solutions/04_primitive_types/primitive_types3.rs @@ -0,0 +1,11 @@ +fn main() { + // An array with 100 elements of the value 42. + let a = [42; 100]; + + 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/rust/rustlings/solutions/04_primitive_types/primitive_types4.rs b/rust/rustlings/solutions/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000..4807e66 --- /dev/null +++ b/rust/rustlings/solutions/04_primitive_types/primitive_types4.rs @@ -0,0 +1,23 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn slice_out_of_array() { + let a = [1, 2, 3, 4, 5]; + // 0 1 2 3 4 <- indices + // ------- + // | + // +--- slice + + // Note that the upper index 4 is excluded. + let nice_slice = &a[1..4]; + assert_eq!([2, 3, 4], nice_slice); + + // The upper index can be included by using the syntax `..=` (with `=` sign) + let nice_slice = &a[1..=3]; + assert_eq!([2, 3, 4], nice_slice); + } +} diff --git a/rust/rustlings/solutions/04_primitive_types/primitive_types5.rs b/rust/rustlings/solutions/04_primitive_types/primitive_types5.rs new file mode 100644 index 0000000..46d7ae8 --- /dev/null +++ b/rust/rustlings/solutions/04_primitive_types/primitive_types5.rs @@ -0,0 +1,8 @@ +fn main() { + let cat = ("Furry McFurson", 3.5); + + // Destructuring the tuple. + let (name, age) = cat; + + println!("{name} is {age} years old"); +} diff --git a/rust/rustlings/solutions/04_primitive_types/primitive_types6.rs b/rust/rustlings/solutions/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000..9b7c277 --- /dev/null +++ b/rust/rustlings/solutions/04_primitive_types/primitive_types6.rs @@ -0,0 +1,16 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn indexing_tuple() { + let numbers = (1, 2, 3); + + // Tuple indexing syntax. + let second = numbers.1; + + assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); + } +} diff --git a/rust/rustlings/solutions/05_vecs/vecs1.rs b/rust/rustlings/solutions/05_vecs/vecs1.rs new file mode 100644 index 0000000..55b5676 --- /dev/null +++ b/rust/rustlings/solutions/05_vecs/vecs1.rs @@ -0,0 +1,23 @@ +fn array_and_vec() -> ([i32; 4], Vec) { + let a = [10, 20, 30, 40]; // Array + + // Used the `vec!` macro. + let v = vec![10, 20, 30, 40]; + + (a, v) +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/solutions/05_vecs/vecs2.rs b/rust/rustlings/solutions/05_vecs/vecs2.rs new file mode 100644 index 0000000..87f7625 --- /dev/null +++ b/rust/rustlings/solutions/05_vecs/vecs2.rs @@ -0,0 +1,55 @@ +fn vec_loop(input: &[i32]) -> Vec { + let mut output = Vec::new(); + + for element in input { + output.push(2 * element); + } + + output +} + +fn vec_map_example(input: &[i32]) -> Vec { + // An example of collecting a vector after mapping. + // We map each element of the `input` slice to its value plus 1. + // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`. + input.iter().map(|element| element + 1).collect() +} + +fn vec_map(input: &[i32]) -> Vec { + // We will dive deeper into iterators, but for now, this is all what you + // had to do! + // Advanced note: This method is more efficient because it automatically + // preallocates enough capacity. This can be done manually in `vec_loop` + // using `Vec::with_capacity(input.len())` instead of `Vec::new()`. + input.iter().map(|element| 2 * element).collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_vec_loop() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_loop(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } + + #[test] + fn test_vec_map_example() { + let input = [1, 2, 3]; + let ans = vec_map_example(&input); + assert_eq!(ans, [2, 3, 4]); + } + + #[test] + fn test_vec_map() { + let input = [2, 4, 6, 8, 10]; + let ans = vec_map(&input); + assert_eq!(ans, [4, 8, 12, 16, 20]); + } +} diff --git a/rust/rustlings/solutions/06_move_semantics/move_semantics1.rs b/rust/rustlings/solutions/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000..ac34e7a --- /dev/null +++ b/rust/rustlings/solutions/06_move_semantics/move_semantics1.rs @@ -0,0 +1,25 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + // ^^^ added + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics1() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + // `vec0` can't be accessed anymore because it is moved to `fill_vec`. + assert_eq!(vec1, vec![22, 44, 66, 88]); + } +} diff --git a/rust/rustlings/solutions/06_move_semantics/move_semantics2.rs b/rust/rustlings/solutions/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000..7bcd33a --- /dev/null +++ b/rust/rustlings/solutions/06_move_semantics/move_semantics2.rs @@ -0,0 +1,28 @@ +fn fill_vec(vec: Vec) -> Vec { + let mut vec = vec; + + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics2() { + let vec0 = vec![22, 44, 66]; + + // Cloning `vec0` so that the clone is moved into `fill_vec`, not `vec0` + // itself. + let vec1 = fill_vec(vec0.clone()); + + assert_eq!(vec0, [22, 44, 66]); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/rust/rustlings/solutions/06_move_semantics/move_semantics3.rs b/rust/rustlings/solutions/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000..7ba4006 --- /dev/null +++ b/rust/rustlings/solutions/06_move_semantics/move_semantics3.rs @@ -0,0 +1,22 @@ +fn fill_vec(mut vec: Vec) -> Vec { + // ^^^ added + vec.push(88); + + vec +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn move_semantics3() { + let vec0 = vec![22, 44, 66]; + let vec1 = fill_vec(vec0); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/rust/rustlings/solutions/06_move_semantics/move_semantics4.rs b/rust/rustlings/solutions/06_move_semantics/move_semantics4.rs new file mode 100644 index 0000000..1a39d4f --- /dev/null +++ b/rust/rustlings/solutions/06_move_semantics/move_semantics4.rs @@ -0,0 +1,19 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn move_semantics4() { + let mut x = Vec::new(); + let y = &mut x; + // `y` used here. + y.push(42); + // The mutable reference `y` is not used anymore, + // therefore a new reference can be created. + let z = &mut x; + z.push(13); + assert_eq!(x, [42, 13]); + } +} diff --git a/rust/rustlings/solutions/06_move_semantics/move_semantics5.rs b/rust/rustlings/solutions/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000..1410e91 --- /dev/null +++ b/rust/rustlings/solutions/06_move_semantics/move_semantics5.rs @@ -0,0 +1,23 @@ +#![allow(clippy::ptr_arg)] + +// Borrows instead of taking ownership. +// It is recommended to use `&str` instead of `&String` here. But this is +// enough for now because we didn't handle strings yet. +fn get_char(data: &String) -> char { + data.chars().last().unwrap() +} + +// Takes ownership instead of borrowing. +fn string_uppercase(mut data: String) { + data = data.to_uppercase(); + + println!("{data}"); +} + +fn main() { + let data = "Rust is great!".to_string(); + + get_char(&data); + + string_uppercase(data); +} diff --git a/rust/rustlings/solutions/07_structs/structs1.rs b/rust/rustlings/solutions/07_structs/structs1.rs new file mode 100644 index 0000000..98fafcc --- /dev/null +++ b/rust/rustlings/solutions/07_structs/structs1.rs @@ -0,0 +1,49 @@ +struct ColorRegularStruct { + red: u8, + green: u8, + blue: u8, +} + +struct ColorTupleStruct(u8, u8, u8); + +#[derive(Debug)] +struct UnitStruct; + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn regular_structs() { + let green = ColorRegularStruct { + red: 0, + green: 255, + blue: 0, + }; + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + let green = ColorTupleStruct(0, 255, 0); + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + let unit_struct = UnitStruct; + let message = format!("{unit_struct:?}s are fun!"); + + assert_eq!(message, "UnitStructs are fun!"); + } +} diff --git a/rust/rustlings/solutions/07_structs/structs2.rs b/rust/rustlings/solutions/07_structs/structs2.rs new file mode 100644 index 0000000..589dd93 --- /dev/null +++ b/rust/rustlings/solutions/07_structs/structs2.rs @@ -0,0 +1,51 @@ +#[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, + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn your_order() { + let order_template = create_order_template(); + + let your_order = Order { + name: String::from("Hacker in Rust"), + count: 1, + // Struct update syntax + ..order_template + }; + + assert_eq!(your_order.name, "Hacker in Rust"); + assert_eq!(your_order.year, order_template.year); + assert_eq!(your_order.made_by_phone, order_template.made_by_phone); + 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/rust/rustlings/solutions/07_structs/structs3.rs b/rust/rustlings/solutions/07_structs/structs3.rs new file mode 100644 index 0000000..3f878cc --- /dev/null +++ b/rust/rustlings/solutions/07_structs/structs3.rs @@ -0,0 +1,83 @@ +#[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) -> Self { + if weight_in_grams < 10 { + // This isn't how you should handle errors in Rust, but we will + // learn about error handling later. + panic!("Can't ship a package with weight below 10 grams"); + } + + Self { + sender_country, + recipient_country, + weight_in_grams, + } + } + + fn is_international(&self) -> bool { + // ^^^^^^^ added + self.sender_country != self.recipient_country + } + + fn get_fees(&self, cents_per_gram: u32) -> u32 { + // ^^^^^^ added + self.weight_in_grams * cents_per_gram + } +} + +fn main() { + // You can optionally experiment 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/rust/rustlings/solutions/08_enums/enums1.rs b/rust/rustlings/solutions/08_enums/enums1.rs new file mode 100644 index 0000000..97a5cc0 --- /dev/null +++ b/rust/rustlings/solutions/08_enums/enums1.rs @@ -0,0 +1,16 @@ +#[derive(Debug)] +enum Message { + Resize, + Move, + Echo, + ChangeColor, + Quit, +} + +fn main() { + println!("{:?}", Message::Resize); + println!("{:?}", Message::Move); + println!("{:?}", Message::Echo); + println!("{:?}", Message::ChangeColor); + println!("{:?}", Message::Quit); +} diff --git a/rust/rustlings/solutions/08_enums/enums2.rs b/rust/rustlings/solutions/08_enums/enums2.rs new file mode 100644 index 0000000..07aee26 --- /dev/null +++ b/rust/rustlings/solutions/08_enums/enums2.rs @@ -0,0 +1,37 @@ +#[derive(Debug)] +struct Point { + x: u64, + y: u64, +} + +#[derive(Debug)] +enum Message { + Resize { width: u64, height: u64 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +impl Message { + fn call(&self) { + println!("{self:?}"); + } +} + +fn main() { + let messages = [ + Message::Resize { + width: 10, + height: 30, + }, + Message::Move(Point { x: 10, y: 15 }), + Message::Echo(String::from("hello world")), + Message::ChangeColor(200, 255, 255), + Message::Quit, + ]; + + for message in &messages { + message.call(); + } +} diff --git a/rust/rustlings/solutions/08_enums/enums3.rs b/rust/rustlings/solutions/08_enums/enums3.rs new file mode 100644 index 0000000..94cf250 --- /dev/null +++ b/rust/rustlings/solutions/08_enums/enums3.rs @@ -0,0 +1,92 @@ +struct Point { + x: u64, + y: u64, +} + +enum Message { + Resize { width: u64, height: u64 }, + Move(Point), + Echo(String), + ChangeColor(u8, u8, u8), + Quit, +} + +struct State { + width: u64, + height: u64, + position: Point, + message: String, + color: (u8, u8, u8), + quit: bool, +} + +impl State { + fn resize(&mut self, width: u64, height: u64) { + self.width = width; + self.height = height; + } + + fn move_position(&mut self, point: Point) { + self.position = point; + } + + fn echo(&mut self, s: String) { + self.message = s; + } + + fn change_color(&mut self, red: u8, green: u8, blue: u8) { + self.color = (red, green, blue); + } + + fn quit(&mut self) { + self.quit = true; + } + + fn process(&mut self, message: Message) { + match message { + Message::Resize { width, height } => self.resize(width, height), + Message::Move(point) => self.move_position(point), + Message::Echo(string) => self.echo(string), + Message::ChangeColor(red, green, blue) => self.change_color(red, green, blue), + Message::Quit => self.quit(), + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_match_message_call() { + let mut state = State { + width: 0, + height: 0, + position: Point { x: 0, y: 0 }, + message: String::from("hello world"), + color: (0, 0, 0), + quit: false, + }; + + state.process(Message::Resize { + width: 10, + height: 30, + }); + state.process(Message::Move(Point { x: 10, y: 15 })); + state.process(Message::Echo(String::from("Hello world!"))); + state.process(Message::ChangeColor(255, 0, 255)); + state.process(Message::Quit); + + assert_eq!(state.width, 10); + assert_eq!(state.height, 30); + assert_eq!(state.position.x, 10); + assert_eq!(state.position.y, 15); + assert_eq!(state.message, "Hello world!"); + assert_eq!(state.color, (255, 0, 255)); + assert!(state.quit); + } +} diff --git a/rust/rustlings/solutions/09_strings/strings1.rs b/rust/rustlings/solutions/09_strings/strings1.rs new file mode 100644 index 0000000..f7ba811 --- /dev/null +++ b/rust/rustlings/solutions/09_strings/strings1.rs @@ -0,0 +1,9 @@ +fn current_favorite_color() -> String { + // Equivalent to `String::from("blue")` + "blue".to_string() +} + +fn main() { + let answer = current_favorite_color(); + println!("My current favorite color is {answer}"); +} diff --git a/rust/rustlings/solutions/09_strings/strings2.rs b/rust/rustlings/solutions/09_strings/strings2.rs new file mode 100644 index 0000000..7de311f --- /dev/null +++ b/rust/rustlings/solutions/09_strings/strings2.rs @@ -0,0 +1,15 @@ +fn is_a_color_word(attempt: &str) -> bool { + attempt == "green" || attempt == "blue" || attempt == "red" +} + +fn main() { + let word = String::from("green"); + + if is_a_color_word(&word) { + // ^ added to have `&String` which is automatically + // coerced to `&str` by the compiler. + println!("That is a color word I know!"); + } else { + println!("That is not a color word I know."); + } +} diff --git a/rust/rustlings/solutions/09_strings/strings3.rs b/rust/rustlings/solutions/09_strings/strings3.rs new file mode 100644 index 0000000..ee6b56a --- /dev/null +++ b/rust/rustlings/solutions/09_strings/strings3.rs @@ -0,0 +1,49 @@ +fn trim_me(input: &str) -> &str { + input.trim() +} + +fn compose_me(input: &str) -> String { + // The macro `format!` has the same syntax as `println!`, but it returns a + // string instead of printing it to the terminal. + // Equivalent to `input.to_string() + " world!"` + format!("{input} world!") +} + +fn replace_me(input: &str) -> String { + input.replace("cars", "balloons") +} + +fn main() { + // You can optionally experiment here. +} + +#[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!"); + assert_eq!(trim_me("Hi!"), "Hi!"); + } + + #[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/rust/rustlings/solutions/09_strings/strings4.rs b/rust/rustlings/solutions/09_strings/strings4.rs new file mode 100644 index 0000000..3c69b97 --- /dev/null +++ b/rust/rustlings/solutions/09_strings/strings4.rs @@ -0,0 +1,38 @@ +fn string_slice(arg: &str) { + println!("{arg}"); +} + +fn string(arg: String) { + println!("{arg}"); +} + +fn main() { + string_slice("blue"); + + string("red".to_string()); + + string(String::from("hi")); + + string("rust is fun!".to_owned()); + + // Here, both answers work. + // `.into()` converts a type into an expected type. + // If it is called where `String` is expected, it will convert `&str` to `String`. + string("nice weather".into()); + // But if it is called where `&str` is expected, then `&str` is kept `&str` since no conversion is needed. + // If you remove the `#[allow(…)]` line, then Clippy will tell you to remove `.into()` below since it is a useless conversion. + #[allow(clippy::useless_conversion)] + string_slice("nice weather".into()); + + string(format!("Interpolation {}", "Station")); + + // WARNING: This is byte indexing, not character indexing. + // Character indexing can be done using `s.chars().nth(INDEX)`. + string_slice(&String::from("abc")[0..1]); + + string_slice(" hello there ".trim()); + + string("Happy Monday!".replace("Mon", "Tues")); + + string("mY sHiFt KeY iS sTiCkY".to_lowercase()); +} diff --git a/rust/rustlings/solutions/10_modules/modules1.rs b/rust/rustlings/solutions/10_modules/modules1.rs new file mode 100644 index 0000000..873b412 --- /dev/null +++ b/rust/rustlings/solutions/10_modules/modules1.rs @@ -0,0 +1,15 @@ +mod sausage_factory { + fn get_secret_recipe() -> String { + String::from("Ginger") + } + + // Added `pub` before `fn` to make the function accessible outside the module. + pub fn make_sausage() { + get_secret_recipe(); + println!("sausage!"); + } +} + +fn main() { + sausage_factory::make_sausage(); +} diff --git a/rust/rustlings/solutions/10_modules/modules2.rs b/rust/rustlings/solutions/10_modules/modules2.rs new file mode 100644 index 0000000..55c316d --- /dev/null +++ b/rust/rustlings/solutions/10_modules/modules2.rs @@ -0,0 +1,23 @@ +mod delicious_snacks { + // Added `pub` and used the expected alias after `as`. + pub use self::fruits::PEAR as fruit; + pub use self::veggies::CUCUMBER as veggie; + + mod fruits { + pub const PEAR: &str = "Pear"; + pub const APPLE: &str = "Apple"; + } + + mod veggies { + pub const CUCUMBER: &str = "Cucumber"; + pub const CARROT: &str = "Carrot"; + } +} + +fn main() { + println!( + "favorite snacks: {} and {}", + delicious_snacks::fruit, + delicious_snacks::veggie, + ); +} diff --git a/rust/rustlings/solutions/10_modules/modules3.rs b/rust/rustlings/solutions/10_modules/modules3.rs new file mode 100644 index 0000000..99ff5a7 --- /dev/null +++ b/rust/rustlings/solutions/10_modules/modules3.rs @@ -0,0 +1,8 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +fn main() { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), + Err(_) => panic!("SystemTime before UNIX EPOCH!"), + } +} diff --git a/rust/rustlings/solutions/11_hashmaps/hashmaps1.rs b/rust/rustlings/solutions/11_hashmaps/hashmaps1.rs new file mode 100644 index 0000000..3a787c4 --- /dev/null +++ b/rust/rustlings/solutions/11_hashmaps/hashmaps1.rs @@ -0,0 +1,42 @@ +// 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 3 different +// types of fruits (e.g apple, banana, mango) in the basket and the total count +// of all the fruits should be at least 5. + +use std::collections::HashMap; + +fn fruit_basket() -> HashMap { + // Declare the hash map. + let mut basket = HashMap::new(); + + // Two bananas are already given for you :) + basket.insert(String::from("banana"), 2); + + // Put more fruits in your basket. + basket.insert(String::from("apple"), 3); + basket.insert(String::from("mango"), 1); + + basket +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/solutions/11_hashmaps/hashmaps2.rs b/rust/rustlings/solutions/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000..75e6ec2 --- /dev/null +++ b/rust/rustlings/solutions/11_hashmaps/hashmaps2.rs @@ -0,0 +1,96 @@ +// 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 the fruits that are already in the basket (Apple, +// Mango, and Lychee). + +use std::collections::HashMap; + +#[derive(Hash, PartialEq, Eq, Debug)] +enum Fruit { + Apple, + Banana, + Mango, + Lychee, + Pineapple, +} + +fn fruit_basket(basket: &mut HashMap) { + let fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + for fruit in fruit_kinds { + // If fruit doesn't exist, insert it with some value. + basket.entry(fruit).or_insert(5); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + // Don't modify this function! + fn get_fruit_basket() -> HashMap { + let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)]; + HashMap::from_iter(content) + } + + #[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 fruit_kinds = [ + Fruit::Apple, + Fruit::Banana, + Fruit::Mango, + Fruit::Lychee, + Fruit::Pineapple, + ]; + + let mut basket = get_fruit_basket(); + fruit_basket(&mut basket); + + for fruit_kind in fruit_kinds { + let Some(amount) = basket.get(&fruit_kind) else { + panic!("Fruit kind {fruit_kind:?} was not found in basket"); + }; + assert!(*amount > 0); + } + } +} diff --git a/rust/rustlings/solutions/11_hashmaps/hashmaps3.rs b/rust/rustlings/solutions/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000..485bf83 --- /dev/null +++ b/rust/rustlings/solutions/11_hashmaps/hashmaps3.rs @@ -0,0 +1,85 @@ +// 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, the total +// number of goals the team scored, and the total number of goals the team +// conceded. + +use std::collections::HashMap; + +// A structure to store the goal details of a team. +#[derive(Default)] +struct TeamScores { + goals_scored: u8, + goals_conceded: u8, +} + +fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { + // The name of the team is the key and its associated struct is the value. + let mut scores = HashMap::<&str, TeamScores>::new(); + + for line in results.lines() { + let mut split_iterator = line.split(','); + // NOTE: We use `unwrap` because we didn't deal with error handling yet. + let team_1_name = split_iterator.next().unwrap(); + let team_2_name = split_iterator.next().unwrap(); + let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); + + // Insert the default with zeros if a team doesn't exist yet. + let team_1 = scores.entry(team_1_name).or_default(); + // Update the values. + team_1.goals_scored += team_1_score; + team_1.goals_conceded += team_2_score; + + // Similarly for the second team. + let team_2 = scores.entry(team_2_name).or_default(); + team_2.goals_scored += team_2_score; + team_2.goals_conceded += team_1_score; + } + + scores +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + const RESULTS: &str = "England,France,4,2 +France,Italy,3,1 +Poland,Spain,2,0 +Germany,England,2,1 +England,Spain,1,0"; + + #[test] + fn build_scores() { + let scores = build_scores_table(RESULTS); + + assert!( + ["England", "France", "Germany", "Italy", "Poland", "Spain"] + .into_iter() + .all(|team_name| scores.contains_key(team_name)) + ); + } + + #[test] + fn validate_team_score_1() { + let scores = build_scores_table(RESULTS); + let team = scores.get("England").unwrap(); + assert_eq!(team.goals_scored, 6); + assert_eq!(team.goals_conceded, 4); + } + + #[test] + fn validate_team_score_2() { + let scores = build_scores_table(RESULTS); + let team = scores.get("Spain").unwrap(); + assert_eq!(team.goals_scored, 0); + assert_eq!(team.goals_conceded, 3); + } +} diff --git a/rust/rustlings/solutions/12_options/options1.rs b/rust/rustlings/solutions/12_options/options1.rs new file mode 100644 index 0000000..4d615dd --- /dev/null +++ b/rust/rustlings/solutions/12_options/options1.rs @@ -0,0 +1,39 @@ +// This function returns how much icecream there is left in the fridge. +// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, +// someone eats it all, so no icecream is left (value 0). Return `None` if +// `hour_of_day` is higher than 23. +fn maybe_icecream(hour_of_day: u16) -> Option { + match hour_of_day { + 0..=21 => Some(5), + 22..=23 => Some(0), + _ => None, + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn raw_value() { + // Using `unwrap` is fine in a test. + let icecreams = maybe_icecream(12).unwrap(); + + assert_eq!(icecreams, 5); + } + + #[test] + fn check_icecream() { + assert_eq!(maybe_icecream(0), Some(5)); + assert_eq!(maybe_icecream(9), Some(5)); + assert_eq!(maybe_icecream(18), Some(5)); + assert_eq!(maybe_icecream(22), Some(0)); + assert_eq!(maybe_icecream(23), Some(0)); + assert_eq!(maybe_icecream(24), None); + assert_eq!(maybe_icecream(25), None); + } +} diff --git a/rust/rustlings/solutions/12_options/options2.rs b/rust/rustlings/solutions/12_options/options2.rs new file mode 100644 index 0000000..0f24665 --- /dev/null +++ b/rust/rustlings/solutions/12_options/options2.rs @@ -0,0 +1,37 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn simple_option() { + let target = "rustlings"; + let optional_target = Some(target); + + // if-let + if let Some(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 { + optional_integers.push(Some(i)); + } + + let mut cursor = range; + + // while-let with nested pattern matching + while let Some(Some(integer)) = optional_integers.pop() { + assert_eq!(integer, cursor); + cursor -= 1; + } + + assert_eq!(cursor, 0); + } +} diff --git a/rust/rustlings/solutions/12_options/options3.rs b/rust/rustlings/solutions/12_options/options3.rs new file mode 100644 index 0000000..c918f71 --- /dev/null +++ b/rust/rustlings/solutions/12_options/options3.rs @@ -0,0 +1,27 @@ +#[derive(Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let optional_point = Some(Point { x: 100, y: 200 }); + + // Solution 1: Matching over the `Option` (not `&Option`) but without moving + // out of the `Some` variant. + match optional_point { + Some(ref p) => println!("Coordinates are {},{}", p.x, p.y), + // ^^^ added + _ => panic!("No match!"), + } + + // Solution 2: Matching over a reference (`&Option`) by added `&` before + // `optional_point`. + match &optional_point { + //^ added + Some(p) => println!("Coordinates are {},{}", p.x, p.y), + _ => panic!("No match!"), + } + + println!("{optional_point:?}"); +} diff --git a/rust/rustlings/solutions/13_error_handling/errors1.rs b/rust/rustlings/solutions/13_error_handling/errors1.rs new file mode 100644 index 0000000..f552ca7 --- /dev/null +++ b/rust/rustlings/solutions/13_error_handling/errors1.rs @@ -0,0 +1,37 @@ +fn generate_nametag_text(name: String) -> Result { + // ^^^^^^ ^^^^^^ + if name.is_empty() { + // `Err(String)` instead of `None`. + Err("Empty names aren't allowed".to_string()) + } else { + // `Ok` instead of `Some`. + Ok(format!("Hi! My name is {name}")) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generates_nametag_text_for_a_nonempty_name() { + assert_eq!( + generate_nametag_text("Beyoncé".to_string()).as_deref(), + Ok("Hi! My name is Beyoncé"), + ); + } + + #[test] + fn explains_why_generating_nametag_text_fails() { + assert_eq!( + generate_nametag_text(String::new()) + .as_ref() + .map_err(|e| e.as_str()), + Err("Empty names aren't allowed"), + ); + } +} diff --git a/rust/rustlings/solutions/13_error_handling/errors2.rs b/rust/rustlings/solutions/13_error_handling/errors2.rs new file mode 100644 index 0000000..f0e144e --- /dev/null +++ b/rust/rustlings/solutions/13_error_handling/errors2.rs @@ -0,0 +1,58 @@ +// 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, we get it as a string. They might have +// typed anything, not just numbers! +// +// Right now, this function isn't handling the error case at all. 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`. 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! + +use std::num::ParseIntError; + +#[allow(unused_variables, clippy::question_mark)] +fn total_cost(item_quantity: &str) -> Result { + let processing_fee = 1; + let cost_per_item = 5; + + // Added `?` to propagate the error. + let qty = item_quantity.parse::()?; + // ^ added + + // Equivalent to this verbose version: + let qty = match item_quantity.parse::() { + Ok(v) => v, + Err(e) => return Err(e), + }; + + Ok(qty * cost_per_item + processing_fee) +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + use std::num::IntErrorKind; + + #[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().kind(), + &IntErrorKind::InvalidDigit, + ); + } +} diff --git a/rust/rustlings/solutions/13_error_handling/errors3.rs b/rust/rustlings/solutions/13_error_handling/errors3.rs new file mode 100644 index 0000000..63f4aba --- /dev/null +++ b/rust/rustlings/solutions/13_error_handling/errors3.rs @@ -0,0 +1,32 @@ +// 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? + +use std::num::ParseIntError; + +// Don't change this function. +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) +} + +fn main() -> Result<(), ParseIntError> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ added + 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."); + } + + // Added this line to return the `Ok` variant of the expected `Result`. + Ok(()) +} diff --git a/rust/rustlings/solutions/13_error_handling/errors4.rs b/rust/rustlings/solutions/13_error_handling/errors4.rs new file mode 100644 index 0000000..70c5f1c --- /dev/null +++ b/rust/rustlings/solutions/13_error_handling/errors4.rs @@ -0,0 +1,42 @@ +use std::cmp::Ordering; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value.cmp(&0) { + Ordering::Less => Err(CreationError::Negative), + Ordering::Equal => Err(CreationError::Zero), + Ordering::Greater => Ok(Self(value as u64)), + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_creation() { + assert_eq!( + PositiveNonzeroInteger::new(10), + Ok(PositiveNonzeroInteger(10)), + ); + assert_eq!( + PositiveNonzeroInteger::new(-10), + Err(CreationError::Negative), + ); + assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); + } +} diff --git a/rust/rustlings/solutions/13_error_handling/errors5.rs b/rust/rustlings/solutions/13_error_handling/errors5.rs new file mode 100644 index 0000000..c1424ee --- /dev/null +++ b/rust/rustlings/solutions/13_error_handling/errors5.rs @@ -0,0 +1,54 @@ +// This exercise is an altered version of the `errors4` exercise. It 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. +// +// 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`. + +use std::error::Error; +use std::fmt; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// This is required so that `CreationError` can implement `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 for CreationError {} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(PositiveNonzeroInteger(x as u64)), + } + } +} + +fn main() -> Result<(), Box> { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} diff --git a/rust/rustlings/solutions/13_error_handling/errors6.rs b/rust/rustlings/solutions/13_error_handling/errors6.rs new file mode 100644 index 0000000..ce18073 --- /dev/null +++ b/rust/rustlings/solutions/13_error_handling/errors6.rs @@ -0,0 +1,106 @@ +// 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. + +use std::num::ParseIntError; + +#[derive(PartialEq, Debug)] +enum CreationError { + Negative, + Zero, +} + +// A custom error type that we will be using in `PositiveNonzeroInteger::parse`. +#[derive(PartialEq, Debug)] +enum ParsePosNonzeroError { + Creation(CreationError), + ParseInt(ParseIntError), +} + +impl ParsePosNonzeroError { + fn from_creation(err: CreationError) -> Self { + Self::Creation(err) + } + + fn from_parse_int(err: ParseIntError) -> Self { + Self::ParseInt(err) + } +} + +// As an alternative solution, implementing the `From` trait allows for the +// automatic conversion from a `ParseIntError` into a `ParsePosNonzeroError` +// using the `?` operator, without the need to call `map_err`. +// +// ``` +// let x: i64 = s.parse()?; +// ``` +// +// Traits like `From` will be dealt with in later exercises. +impl From for ParsePosNonzeroError { + fn from(err: ParseIntError) -> Self { + ParsePosNonzeroError::ParseInt(err) + } +} + +#[derive(PartialEq, Debug)] +struct PositiveNonzeroInteger(u64); + +impl PositiveNonzeroInteger { + fn new(value: i64) -> Result { + match value { + x if x < 0 => Err(CreationError::Negative), + 0 => Err(CreationError::Zero), + x => Ok(Self(x as u64)), + } + } + + fn parse(s: &str) -> Result { + // Return an appropriate error instead of panicking when `parse()` + // returns an error. + let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parse_int)?; + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + Self::new(x).map_err(ParsePosNonzeroError::from_creation) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_parse_error() { + assert!(matches!( + PositiveNonzeroInteger::parse("not a number"), + Err(ParsePosNonzeroError::ParseInt(_)), + )); + } + + #[test] + fn test_negative() { + assert_eq!( + PositiveNonzeroInteger::parse("-555"), + Err(ParsePosNonzeroError::Creation(CreationError::Negative)), + ); + } + + #[test] + fn test_zero() { + assert_eq!( + PositiveNonzeroInteger::parse("0"), + Err(ParsePosNonzeroError::Creation(CreationError::Zero)), + ); + } + + #[test] + fn test_positive() { + let x = PositiveNonzeroInteger::new(42).unwrap(); + assert_eq!(x.0, 42); + assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x)); + } +} diff --git a/rust/rustlings/solutions/14_generics/generics1.rs b/rust/rustlings/solutions/14_generics/generics1.rs new file mode 100644 index 0000000..e2195fd --- /dev/null +++ b/rust/rustlings/solutions/14_generics/generics1.rs @@ -0,0 +1,17 @@ +// `Vec` is generic over the type `T`. In most cases, the compiler is able to +// infer `T`, for example after pushing a value with a concrete type to the vector. +// But in this exercise, the compiler needs some help through a type annotation. + +fn main() { + // `u8` and `i8` can both be converted to `i16`. + let mut numbers: Vec = Vec::new(); + // ^^^^^^^^^^ added + + // Don't change the lines below. + let n1: u8 = 42; + numbers.push(n1.into()); + let n2: i8 = -1; + numbers.push(n2.into()); + + println!("{numbers:?}"); +} diff --git a/rust/rustlings/solutions/14_generics/generics2.rs b/rust/rustlings/solutions/14_generics/generics2.rs new file mode 100644 index 0000000..14f3f7a --- /dev/null +++ b/rust/rustlings/solutions/14_generics/generics2.rs @@ -0,0 +1,28 @@ +struct Wrapper { + value: T, +} + +impl Wrapper { + fn new(value: T) -> Self { + Wrapper { value } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/solutions/15_traits/traits1.rs b/rust/rustlings/solutions/15_traits/traits1.rs new file mode 100644 index 0000000..790873f --- /dev/null +++ b/rust/rustlings/solutions/15_traits/traits1.rs @@ -0,0 +1,32 @@ +// The trait `AppendBar` has only one function which appends "Bar" to any object +// implementing this trait. +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for String { + fn append_bar(self) -> Self { + self + "Bar" + } +} + +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(), "FooBar"); + } + + #[test] + fn is_bar_bar() { + assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); + } +} diff --git a/rust/rustlings/solutions/15_traits/traits2.rs b/rust/rustlings/solutions/15_traits/traits2.rs new file mode 100644 index 0000000..0db93e0 --- /dev/null +++ b/rust/rustlings/solutions/15_traits/traits2.rs @@ -0,0 +1,27 @@ +trait AppendBar { + fn append_bar(self) -> Self; +} + +impl AppendBar for Vec { + fn append_bar(mut self) -> Self { + // ^^^ this is important + self.push(String::from("Bar")); + self + } +} + +fn main() { + // You can optionally experiment here. +} + +#[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(), "Bar"); + assert_eq!(foo.pop().unwrap(), "Foo"); + } +} diff --git a/rust/rustlings/solutions/15_traits/traits3.rs b/rust/rustlings/solutions/15_traits/traits3.rs new file mode 100644 index 0000000..3d8ec85 --- /dev/null +++ b/rust/rustlings/solutions/15_traits/traits3.rs @@ -0,0 +1,36 @@ +trait Licensed { + fn licensing_info(&self) -> String { + "Default license".to_string() + } +} + +struct SomeSoftware { + version_number: i32, +} + +struct OtherSoftware { + version_number: String, +} + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_licensing_info_the_same() { + let licensing_info = "Default license"; + 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/rust/rustlings/solutions/15_traits/traits4.rs b/rust/rustlings/solutions/15_traits/traits4.rs new file mode 100644 index 0000000..3675b8d --- /dev/null +++ b/rust/rustlings/solutions/15_traits/traits4.rs @@ -0,0 +1,35 @@ +trait Licensed { + fn licensing_info(&self) -> String { + "Default license".to_string() + } +} + +struct SomeSoftware; +struct OtherSoftware; + +impl Licensed for SomeSoftware {} +impl Licensed for OtherSoftware {} + +fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool { + // ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ + software1.licensing_info() == software2.licensing_info() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compare_license_information() { + assert!(compare_license_types(SomeSoftware, OtherSoftware)); + } + + #[test] + fn compare_license_information_backwards() { + assert!(compare_license_types(OtherSoftware, SomeSoftware)); + } +} diff --git a/rust/rustlings/solutions/15_traits/traits5.rs b/rust/rustlings/solutions/15_traits/traits5.rs new file mode 100644 index 0000000..1fb426a --- /dev/null +++ b/rust/rustlings/solutions/15_traits/traits5.rs @@ -0,0 +1,39 @@ +trait SomeTrait { + fn some_function(&self) -> bool { + true + } +} + +trait OtherTrait { + fn other_function(&self) -> bool { + true + } +} + +struct SomeStruct; +impl SomeTrait for SomeStruct {} +impl OtherTrait for SomeStruct {} + +struct OtherStruct; +impl SomeTrait for OtherStruct {} +impl OtherTrait for OtherStruct {} + +fn some_func(item: impl SomeTrait + OtherTrait) -> bool { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + item.some_function() && item.other_function() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_some_func() { + assert!(some_func(SomeStruct)); + assert!(some_func(OtherStruct)); + } +} diff --git a/rust/rustlings/solutions/16_lifetimes/lifetimes1.rs b/rust/rustlings/solutions/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000..4f56834 --- /dev/null +++ b/rust/rustlings/solutions/16_lifetimes/lifetimes1.rs @@ -0,0 +1,24 @@ +// 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? + +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + // ^^^^ ^^ ^^ ^^ + if x.len() > y.len() { x } else { y } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_longest() { + assert_eq!(longest("abcd", "123"), "abcd"); + assert_eq!(longest("abc", "1234"), "1234"); + } +} diff --git a/rust/rustlings/solutions/16_lifetimes/lifetimes2.rs b/rust/rustlings/solutions/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000..3ca4909 --- /dev/null +++ b/rust/rustlings/solutions/16_lifetimes/lifetimes2.rs @@ -0,0 +1,29 @@ +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"); + // Solution1: You can move `strings2` out of the inner block so that it is + // not dropped before the print statement. + let string2 = String::from("xyz"); + let result; + { + result = longest(&string1, &string2); + } + println!("The longest string is '{result}'"); + // `string2` dropped at the end of the function. + + // ========================================================================= + + let string1 = String::from("long string is long"); + let result; + { + let string2 = String::from("xyz"); + result = longest(&string1, &string2); + // Solution2: You can move the print statement into the inner block so + // that it is executed before `string2` is dropped. + println!("The longest string is '{result}'"); + // `string2` dropped here (end of the inner scope). + } +} diff --git a/rust/rustlings/solutions/16_lifetimes/lifetimes3.rs b/rust/rustlings/solutions/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000..16a5a68 --- /dev/null +++ b/rust/rustlings/solutions/16_lifetimes/lifetimes3.rs @@ -0,0 +1,18 @@ +// Lifetimes are also needed when structs hold references. + +struct Book<'a> { + // ^^^^ added a lifetime annotation + author: &'a str, + // ^^ + title: &'a str, + // ^^ +} + +fn main() { + let book = Book { + author: "George Orwell", + title: "1984", + }; + + println!("{} by {}", book.title, book.author); +} diff --git a/rust/rustlings/solutions/17_tests/tests1.rs b/rust/rustlings/solutions/17_tests/tests1.rs new file mode 100644 index 0000000..c52b8b1 --- /dev/null +++ b/rust/rustlings/solutions/17_tests/tests1.rs @@ -0,0 +1,24 @@ +// Tests are important to ensure that your code does what you think it should +// do. + +fn is_even(n: i64) -> bool { + n % 2 == 0 +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // When writing unit tests, it is common to import everything from the outer + // module (`super`) using a wildcard. + use super::*; + + #[test] + fn you_can_assert() { + assert!(is_even(0)); + assert!(!is_even(-1)); + // ^ You can assert `false` using the negation operator `!`. + } +} diff --git a/rust/rustlings/solutions/17_tests/tests2.rs b/rust/rustlings/solutions/17_tests/tests2.rs new file mode 100644 index 0000000..39a0005 --- /dev/null +++ b/rust/rustlings/solutions/17_tests/tests2.rs @@ -0,0 +1,22 @@ +// Calculates the power of 2 using a bit shift. +// `1 << n` is equivalent to "2 to the power of n". +fn power_of_2(n: u8) -> u64 { + 1 << n +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn you_can_assert_eq() { + assert_eq!(power_of_2(0), 1); + assert_eq!(power_of_2(1), 2); + assert_eq!(power_of_2(2), 4); + assert_eq!(power_of_2(3), 8); + } +} diff --git a/rust/rustlings/solutions/17_tests/tests3.rs b/rust/rustlings/solutions/17_tests/tests3.rs new file mode 100644 index 0000000..487fdc6 --- /dev/null +++ b/rust/rustlings/solutions/17_tests/tests3.rs @@ -0,0 +1,45 @@ +struct Rectangle { + width: i32, + height: i32, +} + +impl Rectangle { + // Don't change this function. + fn new(width: i32, height: i32) -> Self { + if width <= 0 || height <= 0 { + // Returning a `Result` would be better here. But we want to learn + // how to test functions that can panic. + panic!("Rectangle width and height must be positive"); + } + + Rectangle { width, height } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correct_width_and_height() { + let rect = Rectangle::new(10, 20); + assert_eq!(rect.width, 10); // Check width + assert_eq!(rect.height, 20); // Check height + } + + #[test] + #[should_panic] // Added this attribute to check that the test panics. + fn negative_width() { + let _rect = Rectangle::new(-10, 10); + } + + #[test] + #[should_panic] // Added this attribute to check that the test panics. + fn negative_height() { + let _rect = Rectangle::new(10, -10); + } +} diff --git a/rust/rustlings/solutions/18_iterators/iterators1.rs b/rust/rustlings/solutions/18_iterators/iterators1.rs new file mode 100644 index 0000000..93a6008 --- /dev/null +++ b/rust/rustlings/solutions/18_iterators/iterators1.rs @@ -0,0 +1,26 @@ +// 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. + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn iterators() { + let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"]; + + // Create an iterator over the array. + let mut fav_fruits_iterator = my_fav_fruits.iter(); + + assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); + assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); + assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); + assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); + assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); + assert_eq!(fav_fruits_iterator.next(), None); + // ^^^^ reached the end + } +} diff --git a/rust/rustlings/solutions/18_iterators/iterators2.rs b/rust/rustlings/solutions/18_iterators/iterators2.rs new file mode 100644 index 0000000..db05f29 --- /dev/null +++ b/rust/rustlings/solutions/18_iterators/iterators2.rs @@ -0,0 +1,56 @@ +// In this exercise, you'll learn some of the unique advantages that iterators +// can offer. + +// "hello" -> "Hello" +fn capitalize_first(input: &str) -> String { + let mut chars = input.chars(); + match chars.next() { + None => String::new(), + Some(first) => first.to_uppercase().to_string() + chars.as_str(), + } +} + +// Apply the `capitalize_first` function to a slice of string slices. +// Return a vector of strings. +// ["hello", "world"] -> ["Hello", "World"] +fn capitalize_words_vector(words: &[&str]) -> Vec { + words.iter().map(|word| capitalize_first(word)).collect() +} + +// Apply the `capitalize_first` function again to a slice of string +// slices. Return a single string. +// ["hello", " ", "world"] -> "Hello World" +fn capitalize_words_string(words: &[&str]) -> String { + words.iter().map(|word| capitalize_first(word)).collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[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/rust/rustlings/solutions/18_iterators/iterators3.rs b/rust/rustlings/solutions/18_iterators/iterators3.rs new file mode 100644 index 0000000..1d5d67f --- /dev/null +++ b/rust/rustlings/solutions/18_iterators/iterators3.rs @@ -0,0 +1,88 @@ +#[derive(Debug, PartialEq, Eq)] +enum DivisionError { + // Example: 42 / 0 + DivideByZero, + // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1` + IntegerOverflow, + // Example: 5 / 2 = 2.5 + NotDivisible, +} + +fn divide(a: i64, b: i64) -> Result { + if b == 0 { + return Err(DivisionError::DivideByZero); + } + + if a == i64::MIN && b == -1 { + return Err(DivisionError::IntegerOverflow); + } + + if a % b != 0 { + return Err(DivisionError::NotDivisible); + } + + Ok(a / b) +} + +fn result_with_list() -> Result, DivisionError> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // Collects to the expected return type. Returns the first error in the + // division results (if one exists). + division_results.collect() +} + +fn list_of_results() -> Vec> { + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); + // Collects to the expected return type. + division_results.collect() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + assert_eq!(divide(81, -1), Ok(-81)); + assert_eq!(divide(i64::MIN, i64::MIN), Ok(1)); + } + + #[test] + fn test_divide_by_0() { + assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); + } + + #[test] + fn test_integer_overflow() { + assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow)); + } + + #[test] + fn test_not_divisible() { + assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); + } + + #[test] + fn test_divide_0_by_something() { + assert_eq!(divide(0, 81), Ok(0)); + } + + #[test] + fn test_result_with_list() { + assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]); + } + + #[test] + fn test_list_of_results() { + assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]); + } +} diff --git a/rust/rustlings/solutions/18_iterators/iterators4.rs b/rust/rustlings/solutions/18_iterators/iterators4.rs new file mode 100644 index 0000000..4168835 --- /dev/null +++ b/rust/rustlings/solutions/18_iterators/iterators4.rs @@ -0,0 +1,72 @@ +// 3 possible solutions are presented. + +// With `for` loop and a mutable variable. +fn factorial_for(num: u64) -> u64 { + let mut result = 1; + + for x in 2..=num { + result *= x; + } + + result +} + +// Equivalent to `factorial_for` but shorter and without a `for` loop and +// mutable variables. +fn factorial_fold(num: u64) -> u64 { + // Case num==0: The iterator 2..=0 is empty + // -> The initial value of `fold` is returned which is 1. + // Case num==1: The iterator 2..=1 is also empty + // -> The initial value 1 is returned. + // Case num==2: The iterator 2..=2 contains one element + // -> The initial value 1 is multiplied by 2 and the result + // is returned. + // Case num==3: The iterator 2..=3 contains 2 elements + // -> 1 * 2 is calculated, then the result 2 is multiplied by + // the second element 3 so the result 6 is returned. + // And so on… + #[allow(clippy::unnecessary_fold)] + (2..=num).fold(1, |acc, x| acc * x) +} + +// Equivalent to `factorial_fold` but with a built-in method that is suggested +// by Clippy. +fn factorial_product(num: u64) -> u64 { + (2..=num).product() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn factorial_of_0() { + assert_eq!(factorial_for(0), 1); + assert_eq!(factorial_fold(0), 1); + assert_eq!(factorial_product(0), 1); + } + + #[test] + fn factorial_of_1() { + assert_eq!(factorial_for(1), 1); + assert_eq!(factorial_fold(1), 1); + assert_eq!(factorial_product(1), 1); + } + #[test] + fn factorial_of_2() { + assert_eq!(factorial_for(2), 2); + assert_eq!(factorial_fold(2), 2); + assert_eq!(factorial_product(2), 2); + } + + #[test] + fn factorial_of_4() { + assert_eq!(factorial_for(4), 24); + assert_eq!(factorial_fold(4), 24); + assert_eq!(factorial_product(4), 24); + } +} diff --git a/rust/rustlings/solutions/18_iterators/iterators5.rs b/rust/rustlings/solutions/18_iterators/iterators5.rs new file mode 100644 index 0000000..067a117 --- /dev/null +++ b/rust/rustlings/solutions/18_iterators/iterators5.rs @@ -0,0 +1,168 @@ +// 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 to not use imperative loops (for/while). + +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 hash map with `String` keys and `Progress` values. + // map = { "variables1": Complete, "from_str": None, … } + map.values().filter(|val| **val == value).count() +} + +fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { + let mut count = 0; + for map in collection { + count += count_for(map, value); + } + count +} + +fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] + collection + .iter() + .map(|map| count_iterator(map, value)) + .sum() +} + +// Equivalent to `count_collection_iterator` and `count_iterator`, iterating as +// if the collection was a single container instead of a container of containers +// (and more accurately, a single iterator instead of an iterator of iterators). +fn count_collection_iterator_flat( + collection: &[HashMap], + value: Progress, +) -> usize { + // `collection` is a slice of hash maps. + // collection = [{ "variables1": Complete, "from_str": None, … }, + // { "variables2": Complete, … }, … ] + collection + .iter() + .flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`) + .filter(|val| **val == value) + .count() +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + use Progress::*; + + fn get_map() -> HashMap { + 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> { + 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] + } + + #[test] + fn count_complete() { + let map = get_map(); + assert_eq!(count_iterator(&map, Complete), 3); + } + + #[test] + fn count_some() { + let map = get_map(); + assert_eq!(count_iterator(&map, Some), 1); + } + + #[test] + fn count_none() { + let map = get_map(); + assert_eq!(count_iterator(&map, None), 2); + } + + #[test] + fn count_complete_equals_for() { + let map = get_map(); + let progress_states = [Complete, Some, 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!(count_collection_iterator(&collection, Complete), 6); + assert_eq!(count_collection_iterator_flat(&collection, Complete), 6); + } + + #[test] + fn count_collection_some() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, Some), 1); + assert_eq!(count_collection_iterator_flat(&collection, Some), 1); + } + + #[test] + fn count_collection_none() { + let collection = get_vec_map(); + assert_eq!(count_collection_iterator(&collection, None), 4); + assert_eq!(count_collection_iterator_flat(&collection, None), 4); + } + + #[test] + fn count_collection_equals_for() { + let collection = get_vec_map(); + let progress_states = [Complete, Some, None]; + + for progress_state in progress_states { + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator(&collection, progress_state), + ); + assert_eq!( + count_collection_for(&collection, progress_state), + count_collection_iterator_flat(&collection, progress_state), + ); + } + } +} diff --git a/rust/rustlings/solutions/19_smart_pointers/arc1.rs b/rust/rustlings/solutions/19_smart_pointers/arc1.rs new file mode 100644 index 0000000..bd76189 --- /dev/null +++ b/rust/rustlings/solutions/19_smart_pointers/arc1.rs @@ -0,0 +1,45 @@ +// In this exercise, we are given a `Vec` of `u32` called `numbers` with values +// ranging from 0 to 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, … +// +// Each thread should own a reference-counting pointer to the vector of +// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`. +// +// Don't get distracted by how threads are spawned and joined. We will practice +// that later in the exercises about threads. + +// Don't change the lines below. +#![forbid(unused_imports)] +use std::{sync::Arc, thread}; + +fn main() { + let numbers: Vec<_> = (0..100u32).collect(); + + let shared_numbers = Arc::new(numbers); + // ^^^^^^^^^^^^^^^^^ + + let mut join_handles = Vec::new(); + + for offset in 0..8 { + let child_numbers = Arc::clone(&shared_numbers); + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + + let handle = thread::spawn(move || { + let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); + println!("Sum of offset {offset} is {sum}"); + }); + + join_handles.push(handle); + } + + for handle in join_handles.into_iter() { + handle.join().unwrap(); + } +} diff --git a/rust/rustlings/solutions/19_smart_pointers/box1.rs b/rust/rustlings/solutions/19_smart_pointers/box1.rs new file mode 100644 index 0000000..189cc56 --- /dev/null +++ b/rust/rustlings/solutions/19_smart_pointers/box1.rs @@ -0,0 +1,47 @@ +// 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`. + +#[derive(PartialEq, Debug)] +enum List { + Cons(i32, Box), + Nil, +} + +fn create_empty_list() -> List { + List::Nil +} + +fn create_non_empty_list() -> List { + List::Cons(42, Box::new(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(), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_create_empty_list() { + assert_eq!(create_empty_list(), List::Nil); + } + + #[test] + fn test_create_non_empty_list() { + assert_ne!(create_empty_list(), create_non_empty_list()); + } +} diff --git a/rust/rustlings/solutions/19_smart_pointers/cow1.rs b/rust/rustlings/solutions/19_smart_pointers/cow1.rs new file mode 100644 index 0000000..461143b --- /dev/null +++ b/rust/rustlings/solutions/19_smart_pointers/cow1.rs @@ -0,0 +1,69 @@ +// This exercise explores the `Cow` (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. + +use std::borrow::Cow; + +fn abs_all(input: &mut Cow<[i32]>) { + for ind in 0..input.len() { + let value = input[ind]; + if value < 0 { + // Clones into a vector if not already owned. + input.to_mut()[ind] = -value; + } + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reference_mutation() { + // Clone occurs because `input` needs to be mutated. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + } + + #[test] + fn reference_no_mutation() { + // No clone occurs because `input` doesn't need to be mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(&vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Borrowed(_))); + // ^^^^^^^^^^^^^^^^ + } + + #[test] + fn owned_no_mutation() { + // We can also pass `vec` without `&` so `Cow` owns it directly. In this + // case, no mutation occurs (all numbers are already absolute) and thus + // also no clone. But the result is still owned because it was never + // borrowed or mutated. + let vec = vec![0, 1, 2]; + let mut input = Cow::from(vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + // ^^^^^^^^^^^^^ + } + + #[test] + fn owned_mutation() { + // Of course this is also the case if a mutation does occur (not all + // numbers are absolute). In this case, the call to `to_mut()` in the + // `abs_all` function returns a reference to the same data as before. + let vec = vec![-1, 0, 1]; + let mut input = Cow::from(vec); + abs_all(&mut input); + assert!(matches!(input, Cow::Owned(_))); + // ^^^^^^^^^^^^^ + } +} diff --git a/rust/rustlings/solutions/19_smart_pointers/rc1.rs b/rust/rustlings/solutions/19_smart_pointers/rc1.rs new file mode 100644 index 0000000..edf40eb --- /dev/null +++ b/rust/rustlings/solutions/19_smart_pointers/rc1.rs @@ -0,0 +1,102 @@ +// 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 `Planet`s. The planets take ownership of the sun, indicating that +// they revolve around the sun. + +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:?}!"); + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rc1() { + 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(); + + let saturn = Planet::Saturn(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + let uranus = Planet::Uranus(Rc::clone(&sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + let neptune = Planet::Neptune(Rc::clone(&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 + + drop(earth); + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + + drop(venus); + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + + drop(mercury); + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + assert_eq!(Rc::strong_count(&sun), 1); + } +} diff --git a/rust/rustlings/solutions/20_threads/threads1.rs b/rust/rustlings/solutions/20_threads/threads1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/20_threads/threads1.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/20_threads/threads2.rs b/rust/rustlings/solutions/20_threads/threads2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/20_threads/threads2.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/20_threads/threads3.rs b/rust/rustlings/solutions/20_threads/threads3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/20_threads/threads3.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/21_macros/macros1.rs b/rust/rustlings/solutions/21_macros/macros1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/21_macros/macros1.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/21_macros/macros2.rs b/rust/rustlings/solutions/21_macros/macros2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/21_macros/macros2.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/21_macros/macros3.rs b/rust/rustlings/solutions/21_macros/macros3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/21_macros/macros3.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/21_macros/macros4.rs b/rust/rustlings/solutions/21_macros/macros4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/21_macros/macros4.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/22_clippy/clippy1.rs b/rust/rustlings/solutions/22_clippy/clippy1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/22_clippy/clippy1.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/22_clippy/clippy2.rs b/rust/rustlings/solutions/22_clippy/clippy2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/22_clippy/clippy2.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/22_clippy/clippy3.rs b/rust/rustlings/solutions/22_clippy/clippy3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/22_clippy/clippy3.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/23_conversions/as_ref_mut.rs b/rust/rustlings/solutions/23_conversions/as_ref_mut.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/23_conversions/as_ref_mut.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/23_conversions/from_into.rs b/rust/rustlings/solutions/23_conversions/from_into.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/23_conversions/from_into.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/23_conversions/from_str.rs b/rust/rustlings/solutions/23_conversions/from_str.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/23_conversions/from_str.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/23_conversions/try_from_into.rs b/rust/rustlings/solutions/23_conversions/try_from_into.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/23_conversions/try_from_into.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/23_conversions/using_as.rs b/rust/rustlings/solutions/23_conversions/using_as.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/rust/rustlings/solutions/23_conversions/using_as.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +} diff --git a/rust/rustlings/solutions/README.md b/rust/rustlings/solutions/README.md new file mode 100644 index 0000000..5b5176b --- /dev/null +++ b/rust/rustlings/solutions/README.md @@ -0,0 +1,6 @@ +# Official Rustlings solutions + +Before you finish an exercise, its solution file will only contain an empty `main` function. +The content of this file will be automatically replaced by the actual solution once you finish the exercise. + +Note that these solutions are often only _one possibility_ to solve an exercise. diff --git a/rust/rustlings/solutions/quizzes/quiz1.rs b/rust/rustlings/solutions/quizzes/quiz1.rs new file mode 100644 index 0000000..5503c8c --- /dev/null +++ b/rust/rustlings/solutions/quizzes/quiz1.rs @@ -0,0 +1,30 @@ +// Mary is buying apples. The price of an apple is calculated as follows: +// - An apple costs 2 rustbucks. +// - However, if Mary buys more than 40 apples, the price of each apple in the +// entire order is reduced to only 1 rustbuck! + +fn calculate_price_of_apples(n_apples: u64) -> u64 { + if n_apples > 40 { + n_apples + } else { + 2 * n_apples + } +} + +fn main() { + // You can optionally experiment here. +} + +// Don't change the tests! +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verify_test() { + assert_eq!(calculate_price_of_apples(35), 70); + assert_eq!(calculate_price_of_apples(40), 80); + assert_eq!(calculate_price_of_apples(41), 41); + assert_eq!(calculate_price_of_apples(65), 65); + } +} diff --git a/rust/rustlings/solutions/quizzes/quiz2.rs b/rust/rustlings/solutions/quizzes/quiz2.rs new file mode 100644 index 0000000..8b073b1 --- /dev/null +++ b/rust/rustlings/solutions/quizzes/quiz2.rs @@ -0,0 +1,90 @@ +// Let's build a little machine in the form of a function. As input, we're going +// to give a list of strings and commands. These commands determine what action +// is going to be applied to the string. It can either be: +// - Uppercase the string +// - Trim the string +// - Append "bar" to the string a specified amount of times +// +// The exact form of this will be: +// - The input is going to be a vector of 2-length tuples, +// the first element is the string, the second one is the command. +// - The output element is going to be a vector of strings. + +enum Command { + Uppercase, + Trim, + Append(usize), +} + +mod my_module { + use super::Command; + + // The solution with a loop. Check out `transformer_iter` for a version + // with iterators. + pub fn transformer(input: Vec<(String, Command)>) -> Vec { + let mut output = Vec::new(); + + for (string, command) in input { + // Create the new string. + let new_string = match command { + Command::Uppercase => string.to_uppercase(), + Command::Trim => string.trim().to_string(), + Command::Append(n) => string + &"bar".repeat(n), + }; + + // Push the new string to the output vector. + output.push(new_string); + } + + output + } + + // Equivalent to `transform` but uses an iterator instead of a loop for + // comparison. Don't worry, we will practice iterators later ;) + pub fn transformer_iter(input: Vec<(String, Command)>) -> Vec { + input + .into_iter() + .map(|(string, command)| match command { + Command::Uppercase => string.to_uppercase(), + Command::Trim => string.trim().to_string(), + Command::Append(n) => string + &"bar".repeat(n), + }) + .collect() + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + // Import `transformer`. + use super::my_module::transformer; + + use super::Command; + use super::my_module::transformer_iter; + + #[test] + fn it_works() { + for transformer in [transformer, transformer_iter] { + let input = vec![ + ("hello".to_string(), Command::Uppercase), + (" all roads lead to rome! ".to_string(), Command::Trim), + ("foo".to_string(), Command::Append(1)), + ("bar".to_string(), Command::Append(5)), + ]; + let output = transformer(input); + + assert_eq!( + output, + [ + "HELLO", + "all roads lead to rome!", + "foobar", + "barbarbarbarbarbar", + ] + ); + } + } +} diff --git a/rust/rustlings/solutions/quizzes/quiz3.rs b/rust/rustlings/solutions/quizzes/quiz3.rs new file mode 100644 index 0000000..7b91278 --- /dev/null +++ b/rust/rustlings/solutions/quizzes/quiz3.rs @@ -0,0 +1,65 @@ +// An imaginary magical school has a new report card generation system written +// in Rust! Currently, the system only supports creating report cards where the +// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the +// school also issues alphabetical grades (A+ -> F-) and needs to be able to +// print both types of report card! +// +// Make the necessary code changes in the struct `ReportCard` and the impl +// block to support alphabetical report cards in addition to numerical ones. + +use std::fmt::Display; + +// Make the struct generic over `T`. +struct ReportCard { + // ^^^ + grade: T, + // ^ + student_name: String, + student_age: u8, +} + +// To be able to print the grade, it has to implement the `Display` trait. +impl ReportCard { + // ^^^^^^^ require that `T` implements `Display`. + fn print(&self) -> String { + format!( + "{} ({}) - achieved a grade of {}", + &self.student_name, &self.student_age, &self.grade, + ) + } +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generate_numeric_report_card() { + let report_card = ReportCard { + grade: 2.1, + student_name: "Tom Wriggle".to_string(), + student_age: 12, + }; + assert_eq!( + report_card.print(), + "Tom Wriggle (12) - achieved a grade of 2.1", + ); + } + + #[test] + fn generate_alphabetic_report_card() { + let report_card = ReportCard { + grade: "A+", + student_name: "Gary Plotter".to_string(), + student_age: 11, + }; + assert_eq!( + report_card.print(), + "Gary Plotter (11) - achieved a grade of A+", + ); + } +} diff --git a/rustlings/.gitattributes b/rustlings/.gitattributes deleted file mode 100644 index 52362b3..0000000 --- a/rustlings/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -exercises/** linguist-vendored -solutions/** linguist-vendored diff --git a/rustlings/.gitignore b/rustlings/.gitignore deleted file mode 100644 index 9182e2f..0000000 --- a/rustlings/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -Cargo.lock -target/ -.vscode/ diff --git a/rustlings/.rustlings-state.txt b/rustlings/.rustlings-state.txt deleted file mode 100644 index 7523b62..0000000 --- a/rustlings/.rustlings-state.txt +++ /dev/null @@ -1,83 +0,0 @@ -DON'T EDIT THIS FILE! - -threads1 - -intro1 -intro2 -variables1 -variables2 -variables3 -variables4 -variables5 -variables6 -functions1 -functions2 -functions3 -functions4 -functions5 -if1 -if2 -if3 -quiz1 -primitive_types1 -primitive_types2 -primitive_types3 -primitive_types4 -primitive_types5 -primitive_types6 -vecs1 -vecs2 -move_semantics1 -move_semantics2 -move_semantics3 -move_semantics4 -move_semantics5 -structs1 -structs2 -structs3 -enums1 -enums2 -enums3 -strings1 -strings2 -strings3 -strings4 -modules1 -modules2 -modules3 -hashmaps1 -hashmaps2 -hashmaps3 -quiz2 -options1 -options2 -options3 -errors1 -errors2 -errors3 -errors4 -errors5 -errors6 -generics1 -generics2 -traits1 -traits2 -traits3 -traits4 -traits5 -quiz3 -lifetimes1 -lifetimes2 -lifetimes3 -tests1 -tests2 -tests3 -iterators1 -iterators2 -iterators3 -iterators4 -iterators5 -box1 -rc1 -arc1 -cow1 \ No newline at end of file diff --git a/rustlings/Cargo.toml b/rustlings/Cargo.toml deleted file mode 100644 index 5275c9e..0000000 --- a/rustlings/Cargo.toml +++ /dev/null @@ -1,222 +0,0 @@ -bin = [ - { name = "intro1", path = "exercises/00_intro/intro1.rs" }, - { name = "intro1_sol", path = "solutions/00_intro/intro1.rs" }, - { name = "intro2", path = "exercises/00_intro/intro2.rs" }, - { name = "intro2_sol", path = "solutions/00_intro/intro2.rs" }, - { name = "variables1", path = "exercises/01_variables/variables1.rs" }, - { name = "variables1_sol", path = "solutions/01_variables/variables1.rs" }, - { name = "variables2", path = "exercises/01_variables/variables2.rs" }, - { name = "variables2_sol", path = "solutions/01_variables/variables2.rs" }, - { name = "variables3", path = "exercises/01_variables/variables3.rs" }, - { name = "variables3_sol", path = "solutions/01_variables/variables3.rs" }, - { name = "variables4", path = "exercises/01_variables/variables4.rs" }, - { name = "variables4_sol", path = "solutions/01_variables/variables4.rs" }, - { name = "variables5", path = "exercises/01_variables/variables5.rs" }, - { name = "variables5_sol", path = "solutions/01_variables/variables5.rs" }, - { name = "variables6", path = "exercises/01_variables/variables6.rs" }, - { name = "variables6_sol", path = "solutions/01_variables/variables6.rs" }, - { name = "functions1", path = "exercises/02_functions/functions1.rs" }, - { name = "functions1_sol", path = "solutions/02_functions/functions1.rs" }, - { name = "functions2", path = "exercises/02_functions/functions2.rs" }, - { name = "functions2_sol", path = "solutions/02_functions/functions2.rs" }, - { name = "functions3", path = "exercises/02_functions/functions3.rs" }, - { name = "functions3_sol", path = "solutions/02_functions/functions3.rs" }, - { name = "functions4", path = "exercises/02_functions/functions4.rs" }, - { name = "functions4_sol", path = "solutions/02_functions/functions4.rs" }, - { name = "functions5", path = "exercises/02_functions/functions5.rs" }, - { name = "functions5_sol", path = "solutions/02_functions/functions5.rs" }, - { name = "if1", path = "exercises/03_if/if1.rs" }, - { name = "if1_sol", path = "solutions/03_if/if1.rs" }, - { name = "if2", path = "exercises/03_if/if2.rs" }, - { name = "if2_sol", path = "solutions/03_if/if2.rs" }, - { name = "if3", path = "exercises/03_if/if3.rs" }, - { name = "if3_sol", path = "solutions/03_if/if3.rs" }, - { name = "quiz1", path = "exercises/quizzes/quiz1.rs" }, - { name = "quiz1_sol", path = "solutions/quizzes/quiz1.rs" }, - { name = "primitive_types1", path = "exercises/04_primitive_types/primitive_types1.rs" }, - { name = "primitive_types1_sol", path = "solutions/04_primitive_types/primitive_types1.rs" }, - { name = "primitive_types2", path = "exercises/04_primitive_types/primitive_types2.rs" }, - { name = "primitive_types2_sol", path = "solutions/04_primitive_types/primitive_types2.rs" }, - { name = "primitive_types3", path = "exercises/04_primitive_types/primitive_types3.rs" }, - { name = "primitive_types3_sol", path = "solutions/04_primitive_types/primitive_types3.rs" }, - { name = "primitive_types4", path = "exercises/04_primitive_types/primitive_types4.rs" }, - { name = "primitive_types4_sol", path = "solutions/04_primitive_types/primitive_types4.rs" }, - { name = "primitive_types5", path = "exercises/04_primitive_types/primitive_types5.rs" }, - { name = "primitive_types5_sol", path = "solutions/04_primitive_types/primitive_types5.rs" }, - { name = "primitive_types6", path = "exercises/04_primitive_types/primitive_types6.rs" }, - { name = "primitive_types6_sol", path = "solutions/04_primitive_types/primitive_types6.rs" }, - { name = "vecs1", path = "exercises/05_vecs/vecs1.rs" }, - { name = "vecs1_sol", path = "solutions/05_vecs/vecs1.rs" }, - { name = "vecs2", path = "exercises/05_vecs/vecs2.rs" }, - { name = "vecs2_sol", path = "solutions/05_vecs/vecs2.rs" }, - { name = "move_semantics1", path = "exercises/06_move_semantics/move_semantics1.rs" }, - { name = "move_semantics1_sol", path = "solutions/06_move_semantics/move_semantics1.rs" }, - { name = "move_semantics2", path = "exercises/06_move_semantics/move_semantics2.rs" }, - { name = "move_semantics2_sol", path = "solutions/06_move_semantics/move_semantics2.rs" }, - { name = "move_semantics3", path = "exercises/06_move_semantics/move_semantics3.rs" }, - { name = "move_semantics3_sol", path = "solutions/06_move_semantics/move_semantics3.rs" }, - { name = "move_semantics4", path = "exercises/06_move_semantics/move_semantics4.rs" }, - { name = "move_semantics4_sol", path = "solutions/06_move_semantics/move_semantics4.rs" }, - { name = "move_semantics5", path = "exercises/06_move_semantics/move_semantics5.rs" }, - { name = "move_semantics5_sol", path = "solutions/06_move_semantics/move_semantics5.rs" }, - { name = "structs1", path = "exercises/07_structs/structs1.rs" }, - { name = "structs1_sol", path = "solutions/07_structs/structs1.rs" }, - { name = "structs2", path = "exercises/07_structs/structs2.rs" }, - { name = "structs2_sol", path = "solutions/07_structs/structs2.rs" }, - { name = "structs3", path = "exercises/07_structs/structs3.rs" }, - { name = "structs3_sol", path = "solutions/07_structs/structs3.rs" }, - { name = "enums1", path = "exercises/08_enums/enums1.rs" }, - { name = "enums1_sol", path = "solutions/08_enums/enums1.rs" }, - { name = "enums2", path = "exercises/08_enums/enums2.rs" }, - { name = "enums2_sol", path = "solutions/08_enums/enums2.rs" }, - { name = "enums3", path = "exercises/08_enums/enums3.rs" }, - { name = "enums3_sol", path = "solutions/08_enums/enums3.rs" }, - { name = "strings1", path = "exercises/09_strings/strings1.rs" }, - { name = "strings1_sol", path = "solutions/09_strings/strings1.rs" }, - { name = "strings2", path = "exercises/09_strings/strings2.rs" }, - { name = "strings2_sol", path = "solutions/09_strings/strings2.rs" }, - { name = "strings3", path = "exercises/09_strings/strings3.rs" }, - { name = "strings3_sol", path = "solutions/09_strings/strings3.rs" }, - { name = "strings4", path = "exercises/09_strings/strings4.rs" }, - { name = "strings4_sol", path = "solutions/09_strings/strings4.rs" }, - { name = "modules1", path = "exercises/10_modules/modules1.rs" }, - { name = "modules1_sol", path = "solutions/10_modules/modules1.rs" }, - { name = "modules2", path = "exercises/10_modules/modules2.rs" }, - { name = "modules2_sol", path = "solutions/10_modules/modules2.rs" }, - { name = "modules3", path = "exercises/10_modules/modules3.rs" }, - { name = "modules3_sol", path = "solutions/10_modules/modules3.rs" }, - { name = "hashmaps1", path = "exercises/11_hashmaps/hashmaps1.rs" }, - { name = "hashmaps1_sol", path = "solutions/11_hashmaps/hashmaps1.rs" }, - { name = "hashmaps2", path = "exercises/11_hashmaps/hashmaps2.rs" }, - { name = "hashmaps2_sol", path = "solutions/11_hashmaps/hashmaps2.rs" }, - { name = "hashmaps3", path = "exercises/11_hashmaps/hashmaps3.rs" }, - { name = "hashmaps3_sol", path = "solutions/11_hashmaps/hashmaps3.rs" }, - { name = "quiz2", path = "exercises/quizzes/quiz2.rs" }, - { name = "quiz2_sol", path = "solutions/quizzes/quiz2.rs" }, - { name = "options1", path = "exercises/12_options/options1.rs" }, - { name = "options1_sol", path = "solutions/12_options/options1.rs" }, - { name = "options2", path = "exercises/12_options/options2.rs" }, - { name = "options2_sol", path = "solutions/12_options/options2.rs" }, - { name = "options3", path = "exercises/12_options/options3.rs" }, - { name = "options3_sol", path = "solutions/12_options/options3.rs" }, - { name = "errors1", path = "exercises/13_error_handling/errors1.rs" }, - { name = "errors1_sol", path = "solutions/13_error_handling/errors1.rs" }, - { name = "errors2", path = "exercises/13_error_handling/errors2.rs" }, - { name = "errors2_sol", path = "solutions/13_error_handling/errors2.rs" }, - { name = "errors3", path = "exercises/13_error_handling/errors3.rs" }, - { name = "errors3_sol", path = "solutions/13_error_handling/errors3.rs" }, - { name = "errors4", path = "exercises/13_error_handling/errors4.rs" }, - { name = "errors4_sol", path = "solutions/13_error_handling/errors4.rs" }, - { name = "errors5", path = "exercises/13_error_handling/errors5.rs" }, - { name = "errors5_sol", path = "solutions/13_error_handling/errors5.rs" }, - { name = "errors6", path = "exercises/13_error_handling/errors6.rs" }, - { name = "errors6_sol", path = "solutions/13_error_handling/errors6.rs" }, - { name = "generics1", path = "exercises/14_generics/generics1.rs" }, - { name = "generics1_sol", path = "solutions/14_generics/generics1.rs" }, - { name = "generics2", path = "exercises/14_generics/generics2.rs" }, - { name = "generics2_sol", path = "solutions/14_generics/generics2.rs" }, - { name = "traits1", path = "exercises/15_traits/traits1.rs" }, - { name = "traits1_sol", path = "solutions/15_traits/traits1.rs" }, - { name = "traits2", path = "exercises/15_traits/traits2.rs" }, - { name = "traits2_sol", path = "solutions/15_traits/traits2.rs" }, - { name = "traits3", path = "exercises/15_traits/traits3.rs" }, - { name = "traits3_sol", path = "solutions/15_traits/traits3.rs" }, - { name = "traits4", path = "exercises/15_traits/traits4.rs" }, - { name = "traits4_sol", path = "solutions/15_traits/traits4.rs" }, - { name = "traits5", path = "exercises/15_traits/traits5.rs" }, - { name = "traits5_sol", path = "solutions/15_traits/traits5.rs" }, - { name = "quiz3", path = "exercises/quizzes/quiz3.rs" }, - { name = "quiz3_sol", path = "solutions/quizzes/quiz3.rs" }, - { name = "lifetimes1", path = "exercises/16_lifetimes/lifetimes1.rs" }, - { name = "lifetimes1_sol", path = "solutions/16_lifetimes/lifetimes1.rs" }, - { name = "lifetimes2", path = "exercises/16_lifetimes/lifetimes2.rs" }, - { name = "lifetimes2_sol", path = "solutions/16_lifetimes/lifetimes2.rs" }, - { name = "lifetimes3", path = "exercises/16_lifetimes/lifetimes3.rs" }, - { name = "lifetimes3_sol", path = "solutions/16_lifetimes/lifetimes3.rs" }, - { name = "tests1", path = "exercises/17_tests/tests1.rs" }, - { name = "tests1_sol", path = "solutions/17_tests/tests1.rs" }, - { name = "tests2", path = "exercises/17_tests/tests2.rs" }, - { name = "tests2_sol", path = "solutions/17_tests/tests2.rs" }, - { name = "tests3", path = "exercises/17_tests/tests3.rs" }, - { name = "tests3_sol", path = "solutions/17_tests/tests3.rs" }, - { name = "iterators1", path = "exercises/18_iterators/iterators1.rs" }, - { name = "iterators1_sol", path = "solutions/18_iterators/iterators1.rs" }, - { name = "iterators2", path = "exercises/18_iterators/iterators2.rs" }, - { name = "iterators2_sol", path = "solutions/18_iterators/iterators2.rs" }, - { name = "iterators3", path = "exercises/18_iterators/iterators3.rs" }, - { name = "iterators3_sol", path = "solutions/18_iterators/iterators3.rs" }, - { name = "iterators4", path = "exercises/18_iterators/iterators4.rs" }, - { name = "iterators4_sol", path = "solutions/18_iterators/iterators4.rs" }, - { name = "iterators5", path = "exercises/18_iterators/iterators5.rs" }, - { name = "iterators5_sol", path = "solutions/18_iterators/iterators5.rs" }, - { name = "box1", path = "exercises/19_smart_pointers/box1.rs" }, - { name = "box1_sol", path = "solutions/19_smart_pointers/box1.rs" }, - { name = "rc1", path = "exercises/19_smart_pointers/rc1.rs" }, - { name = "rc1_sol", path = "solutions/19_smart_pointers/rc1.rs" }, - { name = "arc1", path = "exercises/19_smart_pointers/arc1.rs" }, - { name = "arc1_sol", path = "solutions/19_smart_pointers/arc1.rs" }, - { name = "cow1", path = "exercises/19_smart_pointers/cow1.rs" }, - { name = "cow1_sol", path = "solutions/19_smart_pointers/cow1.rs" }, - { name = "threads1", path = "exercises/20_threads/threads1.rs" }, - { name = "threads1_sol", path = "solutions/20_threads/threads1.rs" }, - { name = "threads2", path = "exercises/20_threads/threads2.rs" }, - { name = "threads2_sol", path = "solutions/20_threads/threads2.rs" }, - { name = "threads3", path = "exercises/20_threads/threads3.rs" }, - { name = "threads3_sol", path = "solutions/20_threads/threads3.rs" }, - { name = "macros1", path = "exercises/21_macros/macros1.rs" }, - { name = "macros1_sol", path = "solutions/21_macros/macros1.rs" }, - { name = "macros2", path = "exercises/21_macros/macros2.rs" }, - { name = "macros2_sol", path = "solutions/21_macros/macros2.rs" }, - { name = "macros3", path = "exercises/21_macros/macros3.rs" }, - { name = "macros3_sol", path = "solutions/21_macros/macros3.rs" }, - { name = "macros4", path = "exercises/21_macros/macros4.rs" }, - { name = "macros4_sol", path = "solutions/21_macros/macros4.rs" }, - { name = "clippy1", path = "exercises/22_clippy/clippy1.rs" }, - { name = "clippy1_sol", path = "solutions/22_clippy/clippy1.rs" }, - { name = "clippy2", path = "exercises/22_clippy/clippy2.rs" }, - { name = "clippy2_sol", path = "solutions/22_clippy/clippy2.rs" }, - { name = "clippy3", path = "exercises/22_clippy/clippy3.rs" }, - { name = "clippy3_sol", path = "solutions/22_clippy/clippy3.rs" }, - { name = "using_as", path = "exercises/23_conversions/using_as.rs" }, - { name = "using_as_sol", path = "solutions/23_conversions/using_as.rs" }, - { name = "from_into", path = "exercises/23_conversions/from_into.rs" }, - { name = "from_into_sol", path = "solutions/23_conversions/from_into.rs" }, - { name = "from_str", path = "exercises/23_conversions/from_str.rs" }, - { name = "from_str_sol", path = "solutions/23_conversions/from_str.rs" }, - { name = "try_from_into", path = "exercises/23_conversions/try_from_into.rs" }, - { name = "try_from_into_sol", path = "solutions/23_conversions/try_from_into.rs" }, - { name = "as_ref_mut", path = "exercises/23_conversions/as_ref_mut.rs" }, - { name = "as_ref_mut_sol", path = "solutions/23_conversions/as_ref_mut.rs" }, -] - -[package] -name = "exercises" -edition = "2024" -# Don't publish the exercises on crates.io! -publish = false - -[profile.release] -panic = "abort" - -[profile.dev] -panic = "abort" - -[lints.rust] -# You shouldn't write unsafe code in Rustlings! -unsafe_code = "forbid" -# You don't need unstable features in Rustlings and shouldn't rely on them while learning Rust. -unstable_features = "forbid" -# Dead code warnings can't be avoided in some exercises and might distract while learning. -dead_code = "allow" - -[lints.clippy] -# You forgot a `todo!()`! -todo = "forbid" -# This can only happen by mistake in Rustlings. -empty_loop = "forbid" -# No infinite loops are needed in Rustlings. -infinite_loop = "deny" -# You shouldn't leak memory while still learning Rust! -mem_forget = "deny" -# Currently, there are no disallowed methods. This line avoids problems when developing Rustlings. -disallowed_methods = "allow" diff --git a/rustlings/exercises/00_intro/README.md b/rustlings/exercises/00_intro/README.md deleted file mode 100644 index d32e4a8..0000000 --- a/rustlings/exercises/00_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/rustlings/exercises/00_intro/intro1.rs b/rustlings/exercises/00_intro/intro1.rs deleted file mode 100644 index 440ae83..0000000 --- a/rustlings/exercises/00_intro/intro1.rs +++ /dev/null @@ -1,28 +0,0 @@ -// TODO: 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, enter `n` in the terminal. -// -// The exercise file will be reloaded when you change one of the lines below! -// Try adding a new `println!` and check the updated output in the terminal. - -fn main() { - 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 file of this exercise is `exercises/00_intro/intro1.rs`. Have a look!"); - println!("The current exercise path will be always shown under the progress bar."); - println!("You can click on the path to open the exercise file in your editor."); - println!(); - println!("New line"); - println!( " another line "); - println!(r#" yet another line"#); -} diff --git a/rustlings/exercises/00_intro/intro2.rs b/rustlings/exercises/00_intro/intro2.rs deleted file mode 100644 index e0b5e27..0000000 --- a/rustlings/exercises/00_intro/intro2.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - println!("Hello world!"); -} diff --git a/rustlings/exercises/01_variables/README.md b/rustlings/exercises/01_variables/README.md deleted file mode 100644 index 5ba2efc..0000000 --- a/rustlings/exercises/01_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/rustlings/exercises/01_variables/variables1.rs b/rustlings/exercises/01_variables/variables1.rs deleted file mode 100644 index 2df7df8..0000000 --- a/rustlings/exercises/01_variables/variables1.rs +++ /dev/null @@ -1,5 +0,0 @@ -fn main() { - let x = 5; - - println!("x has the value {x}"); -} diff --git a/rustlings/exercises/01_variables/variables2.rs b/rustlings/exercises/01_variables/variables2.rs deleted file mode 100644 index b35a0bf..0000000 --- a/rustlings/exercises/01_variables/variables2.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn main() { - let x = 10; - - if x == 10 { - println!("x is ten!"); - } else { - println!("x is not ten!"); - } -} diff --git a/rustlings/exercises/01_variables/variables3.rs b/rustlings/exercises/01_variables/variables3.rs deleted file mode 100644 index 47b2be4..0000000 --- a/rustlings/exercises/01_variables/variables3.rs +++ /dev/null @@ -1,5 +0,0 @@ -fn main() { - let x = 10; - - println!("Number {x}"); -} diff --git a/rustlings/exercises/01_variables/variables4.rs b/rustlings/exercises/01_variables/variables4.rs deleted file mode 100644 index d2967ea..0000000 --- a/rustlings/exercises/01_variables/variables4.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - let mut x = 3; - println!("Number {x}"); - - x = 5; // Don't change this line - println!("Number {x}"); -} diff --git a/rustlings/exercises/01_variables/variables5.rs b/rustlings/exercises/01_variables/variables5.rs deleted file mode 100644 index be94598..0000000 --- a/rustlings/exercises/01_variables/variables5.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - let number = "T-H-R-E-E"; // Don't change this line - println!("Spell a number: {number}"); - - let number = 3; - println!("Number plus two is: {}", number + 2); -} diff --git a/rustlings/exercises/01_variables/variables6.rs b/rustlings/exercises/01_variables/variables6.rs deleted file mode 100644 index c40e572..0000000 --- a/rustlings/exercises/01_variables/variables6.rs +++ /dev/null @@ -1,5 +0,0 @@ -const NUMBER: i32 = 3; - -fn main() { - println!("Number: {NUMBER}"); -} diff --git a/rustlings/exercises/02_functions/README.md b/rustlings/exercises/02_functions/README.md deleted file mode 100644 index 6662d0d..0000000 --- a/rustlings/exercises/02_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/rustlings/exercises/02_functions/functions1.rs b/rustlings/exercises/02_functions/functions1.rs deleted file mode 100644 index 5dbae07..0000000 --- a/rustlings/exercises/02_functions/functions1.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn call_me() { - println!("call_me()"); -} - -fn main() { - call_me(); // Don't change this line -} diff --git a/rustlings/exercises/02_functions/functions2.rs b/rustlings/exercises/02_functions/functions2.rs deleted file mode 100644 index 27f2cc7..0000000 --- a/rustlings/exercises/02_functions/functions2.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn call_me(num: u32) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} - -fn main() { - call_me(3); -} diff --git a/rustlings/exercises/02_functions/functions3.rs b/rustlings/exercises/02_functions/functions3.rs deleted file mode 100644 index 88dff5b..0000000 --- a/rustlings/exercises/02_functions/functions3.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn call_me(num: u8) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} - -fn main() { - call_me(3); -} diff --git a/rustlings/exercises/02_functions/functions4.rs b/rustlings/exercises/02_functions/functions4.rs deleted file mode 100644 index 2c5a3b0..0000000 --- a/rustlings/exercises/02_functions/functions4.rs +++ /dev/null @@ -1,17 +0,0 @@ -fn is_even(num: i64) -> bool { - num % 2 == 0 -} - -// TODO: Fix the function signature. -fn sale_price(price: i64) -> i64 { - if is_even(price) { - price - 10 - } else { - price - 3 - } -} - -fn main() { - let original_price = 51; - println!("Your sale price is {}", sale_price(original_price)); -} diff --git a/rustlings/exercises/02_functions/functions5.rs b/rustlings/exercises/02_functions/functions5.rs deleted file mode 100644 index 024010f..0000000 --- a/rustlings/exercises/02_functions/functions5.rs +++ /dev/null @@ -1,8 +0,0 @@ -fn square(num: i32) -> i32 { - num * num -} - -fn main() { - let answer = square(3); - println!("The square of 3 is {answer}"); -} diff --git a/rustlings/exercises/03_if/README.md b/rustlings/exercises/03_if/README.md deleted file mode 100644 index b52c392..0000000 --- a/rustlings/exercises/03_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/rustlings/exercises/03_if/if1.rs b/rustlings/exercises/03_if/if1.rs deleted file mode 100644 index 079c671..0000000 --- a/rustlings/exercises/03_if/if1.rs +++ /dev/null @@ -1,32 +0,0 @@ -fn bigger(a: i32, b: i32) -> i32 { - if a > b { - a - } else { - b - } -} - -fn main() { - // You can optionally experiment here. -} - -// 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/rustlings/exercises/03_if/if2.rs b/rustlings/exercises/03_if/if2.rs deleted file mode 100644 index 8104487..0000000 --- a/rustlings/exercises/03_if/if2.rs +++ /dev/null @@ -1,39 +0,0 @@ -// TODO: Fix the compiler error on this function. -fn picky_eater(food: &str) -> &str { - if food == "strawberry" { - "Yummy!" - } else if food == "potato" { - "I guess I can eat that." - } else { - "No thanks!" - } -} - -fn main() { - // You can optionally experiment here. -} - -// TODO: Read the tests to understand the desired behavior. -// Make all tests pass without changing them. -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn yummy_food() { - // This means that calling `picky_eater` with the argument "strawberry" should return "Yummy!". - assert_eq!(picky_eater("strawberry"), "Yummy!"); - } - - #[test] - fn neutral_food() { - assert_eq!(picky_eater("potato"), "I guess I can eat that."); - } - - #[test] - fn default_disliked_food() { - assert_eq!(picky_eater("broccoli"), "No thanks!"); - assert_eq!(picky_eater("gummy bears"), "No thanks!"); - assert_eq!(picky_eater("literally anything"), "No thanks!"); - } -} diff --git a/rustlings/exercises/03_if/if3.rs b/rustlings/exercises/03_if/if3.rs deleted file mode 100644 index fee96f8..0000000 --- a/rustlings/exercises/03_if/if3.rs +++ /dev/null @@ -1,52 +0,0 @@ -fn animal_habitat(animal: &str) -> &str { - let identifier = if animal == "crab" { - 1 - } else if animal == "gopher" { - 2 - } else if animal == "snake" { - 3 - } else { - 0 - }; - - // Don't change the expression below! - if identifier == 1 { - "Beach" - } else if identifier == 2 { - "Burrow" - } else if identifier == 3 { - "Desert" - } else { - "Unknown" - } -} - -fn main() { - // You can optionally experiment here. -} - -// Don't change the tests! -#[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/rustlings/exercises/04_primitive_types/README.md b/rustlings/exercises/04_primitive_types/README.md deleted file mode 100644 index d67668a..0000000 --- a/rustlings/exercises/04_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/book/ch03-02-data-types.html) -- [The Slice Type](https://doc.rust-lang.org/book/ch04-03-slices.html) diff --git a/rustlings/exercises/04_primitive_types/primitive_types1.rs b/rustlings/exercises/04_primitive_types/primitive_types1.rs deleted file mode 100644 index 778c0f6..0000000 --- a/rustlings/exercises/04_primitive_types/primitive_types1.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Booleans (`bool`) - -fn main() { - let is_morning = true; - if is_morning { - println!("Good morning!"); - } - - let is_evening = !is_morning; - if is_evening { - println!("Good evening!"); - } -} diff --git a/rustlings/exercises/04_primitive_types/primitive_types2.rs b/rustlings/exercises/04_primitive_types/primitive_types2.rs deleted file mode 100644 index a45f84d..0000000 --- a/rustlings/exercises/04_primitive_types/primitive_types2.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Characters (`char`) - -fn main() { - // 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 your_character = '😉'; - if your_character.is_alphabetic() { - println!("Alphabetical!"); - } else if your_character.is_numeric() { - println!("Numerical!"); - } else { - println!("Neither alphabetic nor numeric!"); - } -} diff --git a/rustlings/exercises/04_primitive_types/primitive_types3.rs b/rustlings/exercises/04_primitive_types/primitive_types3.rs deleted file mode 100644 index c5a259d..0000000 --- a/rustlings/exercises/04_primitive_types/primitive_types3.rs +++ /dev/null @@ -1,10 +0,0 @@ -fn main() { - let a = [0; 1000]; - - 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/rustlings/exercises/04_primitive_types/primitive_types4.rs b/rustlings/exercises/04_primitive_types/primitive_types4.rs deleted file mode 100644 index 81af3e2..0000000 --- a/rustlings/exercises/04_primitive_types/primitive_types4.rs +++ /dev/null @@ -1,15 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn slice_out_of_array() { - let a = [1, 2, 3, 4, 5]; - - let nice_slice = &a[1..4]; - - assert_eq!([2, 3, 4], nice_slice); - } -} diff --git a/rustlings/exercises/04_primitive_types/primitive_types5.rs b/rustlings/exercises/04_primitive_types/primitive_types5.rs deleted file mode 100644 index a3e60d8..0000000 --- a/rustlings/exercises/04_primitive_types/primitive_types5.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - let cat = ("Furry McFurson", 3.5); - - let (name, age) = cat; - - println!("{name} is {age} years old"); -} diff --git a/rustlings/exercises/04_primitive_types/primitive_types6.rs b/rustlings/exercises/04_primitive_types/primitive_types6.rs deleted file mode 100644 index dec639a..0000000 --- a/rustlings/exercises/04_primitive_types/primitive_types6.rs +++ /dev/null @@ -1,15 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn indexing_tuple() { - let numbers = (1, 2, 3); - - let second = numbers.1; - - assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); - } -} diff --git a/rustlings/exercises/05_vecs/README.md b/rustlings/exercises/05_vecs/README.md deleted file mode 100644 index e1b6128..0000000 --- a/rustlings/exercises/05_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/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/rustlings/exercises/05_vecs/vecs1.rs b/rustlings/exercises/05_vecs/vecs1.rs deleted file mode 100644 index f976c84..0000000 --- a/rustlings/exercises/05_vecs/vecs1.rs +++ /dev/null @@ -1,22 +0,0 @@ -fn array_and_vec() -> ([i32; 4], Vec) { - let a = [10, 20, 30, 40]; // Array - - let v = vec![10, 20, 30, 40]; - - (a, v) -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/exercises/05_vecs/vecs2.rs b/rustlings/exercises/05_vecs/vecs2.rs deleted file mode 100644 index 1ec77f7..0000000 --- a/rustlings/exercises/05_vecs/vecs2.rs +++ /dev/null @@ -1,61 +0,0 @@ -fn vec_loop(input: &[i32]) -> Vec { - let mut output = Vec::new(); - - for element in input { - // TODO: Multiply each element in the `input` slice by 2 and push it to - // the `output` vector. - output.push(element * 2); - } - - output -} - -fn vec_map_example(input: &[i32]) -> Vec { - // An example of collecting a vector after mapping. - // We map each element of the `input` slice to its value plus 1. - // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`. - input.iter().map(|element| element + 1).collect() -} - -fn vec_map(input: &[i32]) -> Vec { - // TODO: Here, we also want to multiply each element in the `input` slice - // by 2, but with iterator mapping instead of manually pushing into an empty - // vector. - // See the example in the function `vec_map_example` above. - input - .iter() - .map(|element| { - element * 2 - }) - .collect() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_vec_loop() { - let input = [2, 4, 6, 8, 10]; - let ans = vec_loop(&input); - assert_eq!(ans, [4, 8, 12, 16, 20]); - } - - #[test] - fn test_vec_map_example() { - let input = [1, 2, 3]; - let ans = vec_map_example(&input); - assert_eq!(ans, [2, 3, 4]); - } - - #[test] - fn test_vec_map() { - let input = [2, 4, 6, 8, 10]; - let ans = vec_map(&input); - assert_eq!(ans, [4, 8, 12, 16, 20]); - } -} diff --git a/rustlings/exercises/06_move_semantics/README.md b/rustlings/exercises/06_move_semantics/README.md deleted file mode 100644 index 54ddd8e..0000000 --- a/rustlings/exercises/06_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/rustlings/exercises/06_move_semantics/move_semantics1.rs b/rustlings/exercises/06_move_semantics/move_semantics1.rs deleted file mode 100644 index 9385f28..0000000 --- a/rustlings/exercises/06_move_semantics/move_semantics1.rs +++ /dev/null @@ -1,23 +0,0 @@ -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - - vec.push(88); - - vec -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn move_semantics1() { - let vec0 = vec![22, 44, 66]; - let vec1 = fill_vec(vec0); - assert_eq!(vec1, vec![22, 44, 66, 88]); - } -} diff --git a/rustlings/exercises/06_move_semantics/move_semantics2.rs b/rustlings/exercises/06_move_semantics/move_semantics2.rs deleted file mode 100644 index e205b81..0000000 --- a/rustlings/exercises/06_move_semantics/move_semantics2.rs +++ /dev/null @@ -1,28 +0,0 @@ -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - - vec.push(88); - - vec -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - // TODO: Make both vectors `vec0` and `vec1` accessible at the same time to - // fix the compiler error in the test. - #[test] - fn move_semantics2() { - let vec0 = vec![22, 44, 66]; - - let vec1 = fill_vec(vec0.clone()); - - assert_eq!(vec0, [22, 44, 66]); - assert_eq!(vec1, [22, 44, 66, 88]); - } -} diff --git a/rustlings/exercises/06_move_semantics/move_semantics3.rs b/rustlings/exercises/06_move_semantics/move_semantics3.rs deleted file mode 100644 index 4a90c21..0000000 --- a/rustlings/exercises/06_move_semantics/move_semantics3.rs +++ /dev/null @@ -1,22 +0,0 @@ -// TODO: Fix the compiler error in the function without adding any new line. -fn fill_vec(mut vec: Vec) -> Vec { - vec.push(88); - - vec -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn move_semantics3() { - let vec0 = vec![22, 44, 66]; - let vec1 = fill_vec(vec0); - assert_eq!(vec1, [22, 44, 66, 88]); - } -} diff --git a/rustlings/exercises/06_move_semantics/move_semantics4.rs b/rustlings/exercises/06_move_semantics/move_semantics4.rs deleted file mode 100644 index 89b412f..0000000 --- a/rustlings/exercises/06_move_semantics/move_semantics4.rs +++ /dev/null @@ -1,18 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - // TODO: Fix the compiler errors only by reordering the lines in the test. - // Don't add, change or remove any line. - #[test] - fn move_semantics4() { - let mut x = Vec::new(); - let y = &mut x; - y.push(42); - let z = &mut x; - z.push(13); - assert_eq!(x, [42, 13]); - } -} diff --git a/rustlings/exercises/06_move_semantics/move_semantics5.rs b/rustlings/exercises/06_move_semantics/move_semantics5.rs deleted file mode 100644 index 78d8c77..0000000 --- a/rustlings/exercises/06_move_semantics/move_semantics5.rs +++ /dev/null @@ -1,24 +0,0 @@ -#![allow(clippy::ptr_arg)] - -// TODO: Fix the compiler errors without changing anything except adding or -// removing references (the character `&`). - -// Shouldn't 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}"); -} - -fn main() { - let data = "Rust is great!".to_string(); - - get_char(&data); - - string_uppercase(data); -} diff --git a/rustlings/exercises/07_structs/README.md b/rustlings/exercises/07_structs/README.md deleted file mode 100644 index 3fc1fdc..0000000 --- a/rustlings/exercises/07_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/rustlings/exercises/07_structs/structs1.rs b/rustlings/exercises/07_structs/structs1.rs deleted file mode 100644 index 8376a98..0000000 --- a/rustlings/exercises/07_structs/structs1.rs +++ /dev/null @@ -1,50 +0,0 @@ -struct ColorRegularStruct { - red: u8, - green: u8, - blue: u8, -} - -struct ColorTupleStruct(u8, u8, u8); - -#[derive(Debug)] -struct UnitStruct; - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn regular_structs() { - let green = ColorRegularStruct { - red: 0, - green: 255, - blue: 0, - }; - - assert_eq!(green.red, 0); - assert_eq!(green.green, 255); - assert_eq!(green.blue, 0); - } - - #[test] - fn tuple_structs() { - let green = ColorTupleStruct(0, 255, 0 ); - - assert_eq!(green.0, 0); - assert_eq!(green.1, 255); - assert_eq!(green.2, 0); - } - - #[test] - fn unit_structs() { - let unit_struct = UnitStruct; - - let message = format!("{unit_struct:?}s are fun!"); - - assert_eq!(message, "UnitStructs are fun!"); - } -} diff --git a/rustlings/exercises/07_structs/structs2.rs b/rustlings/exercises/07_structs/structs2.rs deleted file mode 100644 index 2539e31..0000000 --- a/rustlings/exercises/07_structs/structs2.rs +++ /dev/null @@ -1,50 +0,0 @@ -#[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, - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn your_order() { - let order_template = create_order_template(); - - let your_order = Order { - name: String::from("Hacker in Rust"), - count: 1, - ..order_template - }; - - assert_eq!(your_order.name, "Hacker in Rust"); - assert_eq!(your_order.year, order_template.year); - assert_eq!(your_order.made_by_phone, order_template.made_by_phone); - 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/rustlings/exercises/07_structs/structs3.rs b/rustlings/exercises/07_structs/structs3.rs deleted file mode 100644 index d24da27..0000000 --- a/rustlings/exercises/07_structs/structs3.rs +++ /dev/null @@ -1,84 +0,0 @@ -// 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. - -#[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) -> Self { - if weight_in_grams < 10 { - // This isn't how you should handle errors in Rust, but we will - // learn about error handling later. - panic!("Can't ship a package with weight below 10 grams"); - } - - Self { - sender_country, - recipient_country, - weight_in_grams, - } - } - - fn is_international(&self) -> bool { - self.sender_country != self.recipient_country - } - - fn get_fees(&self, cents_per_gram: u32) -> u32 { - self.weight_in_grams * cents_per_gram - } -} - -fn main() { - // You can optionally experiment 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/rustlings/exercises/08_enums/README.md b/rustlings/exercises/08_enums/README.md deleted file mode 100644 index b05cb42..0000000 --- a/rustlings/exercises/08_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/ch19-03-pattern-syntax.html) diff --git a/rustlings/exercises/08_enums/enums1.rs b/rustlings/exercises/08_enums/enums1.rs deleted file mode 100644 index 97a5cc0..0000000 --- a/rustlings/exercises/08_enums/enums1.rs +++ /dev/null @@ -1,16 +0,0 @@ -#[derive(Debug)] -enum Message { - Resize, - Move, - Echo, - ChangeColor, - Quit, -} - -fn main() { - println!("{:?}", Message::Resize); - println!("{:?}", Message::Move); - println!("{:?}", Message::Echo); - println!("{:?}", Message::ChangeColor); - println!("{:?}", Message::Quit); -} diff --git a/rustlings/exercises/08_enums/enums2.rs b/rustlings/exercises/08_enums/enums2.rs deleted file mode 100644 index 4a2d5ac..0000000 --- a/rustlings/exercises/08_enums/enums2.rs +++ /dev/null @@ -1,40 +0,0 @@ -#[derive(Debug)] -struct Point { - x: u64, - y: u64, -} - -#[derive(Debug)] -enum Message { - Resize { - width: u64, - height: u64, - }, - Move(Point), - Echo(String), - ChangeColor(u8, u8, u8), - Quit, -} - -impl Message { - fn call(&self) { - println!("{self:?}"); - } -} - -fn main() { - let messages = [ - Message::Resize { - width: 10, - height: 30, - }, - Message::Move(Point { x: 10, y: 15 }), - Message::Echo(String::from("hello world")), - Message::ChangeColor(200, 255, 255), - Message::Quit, - ]; - - for message in &messages { - message.call(); - } -} diff --git a/rustlings/exercises/08_enums/enums3.rs b/rustlings/exercises/08_enums/enums3.rs deleted file mode 100644 index bf01af3..0000000 --- a/rustlings/exercises/08_enums/enums3.rs +++ /dev/null @@ -1,93 +0,0 @@ -struct Point { - x: u64, - y: u64, -} - -enum Message { - Resize { width: u64, height: u64 }, - Move(Point), - Echo(String), - ChangeColor(u8, u8, u8), - Quit, -} - -struct State { - width: u64, - height: u64, - position: Point, - message: String, - // RGB color composed of red, green and blue. - color: (u8, u8, u8), - quit: bool, -} - -impl State { - fn resize(&mut self, width: u64, height: u64) { - self.width = width; - self.height = height; - } - - fn move_position(&mut self, point: Point) { - self.position = point; - } - - fn echo(&mut self, s: String) { - self.message = s; - } - - fn change_color(&mut self, red: u8, green: u8, blue: u8) { - self.color = (red, green, blue); - } - - fn quit(&mut self) { - self.quit = true; - } - - fn process(&mut self, message: Message) { - match message { - Message::Resize { width, height } => self.resize(width, height), - Message::Move(point) => self.move_position(point), - Message::Echo(s) => self.echo(s), - Message::ChangeColor(red, green, blue) => self.change_color(red, green, blue), - Message::Quit => self.quit(), - } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_match_message_call() { - let mut state = State { - width: 0, - height: 0, - position: Point { x: 0, y: 0 }, - message: String::from("hello world"), - color: (0, 0, 0), - quit: false, - }; - - state.process(Message::Resize { - width: 10, - height: 30, - }); - state.process(Message::Move(Point { x: 10, y: 15 })); - state.process(Message::Echo(String::from("Hello world!"))); - state.process(Message::ChangeColor(255, 0, 255)); - state.process(Message::Quit); - - assert_eq!(state.width, 10); - assert_eq!(state.height, 30); - assert_eq!(state.position.x, 10); - assert_eq!(state.position.y, 15); - assert_eq!(state.message, "Hello world!"); - assert_eq!(state.color, (255, 0, 255)); - assert!(state.quit); - } -} diff --git a/rustlings/exercises/09_strings/README.md b/rustlings/exercises/09_strings/README.md deleted file mode 100644 index fa2104c..0000000 --- a/rustlings/exercises/09_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/rustlings/exercises/09_strings/strings1.rs b/rustlings/exercises/09_strings/strings1.rs deleted file mode 100644 index 482e5de..0000000 --- a/rustlings/exercises/09_strings/strings1.rs +++ /dev/null @@ -1,8 +0,0 @@ -fn current_favorite_color() -> String { - String::from("blue") -} - -fn main() { - let answer = current_favorite_color(); - println!("My current favorite color is {answer}"); -} diff --git a/rustlings/exercises/09_strings/strings2.rs b/rustlings/exercises/09_strings/strings2.rs deleted file mode 100644 index b03094f..0000000 --- a/rustlings/exercises/09_strings/strings2.rs +++ /dev/null @@ -1,13 +0,0 @@ -fn is_a_color_word(attempt: &str) -> bool { - attempt == "green" || attempt == "blue" || attempt == "red" -} - -fn main() { - let word = String::from("green"); // Don't change 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."); - } -} diff --git a/rustlings/exercises/09_strings/strings3.rs b/rustlings/exercises/09_strings/strings3.rs deleted file mode 100644 index 3543ad5..0000000 --- a/rustlings/exercises/09_strings/strings3.rs +++ /dev/null @@ -1,46 +0,0 @@ -fn trim_me(input: &str) -> &str { - input.trim() -} - -fn compose_me(input: &str) -> String { - String::from(input) + " world!" -} - -fn replace_me(input: &str) -> String { - String::from(input).replace("cars", "balloons") -} - -fn main() { - // You can optionally experiment here. -} - -#[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!"); - assert_eq!(trim_me("Hi!"), "Hi!"); - } - - #[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/rustlings/exercises/09_strings/strings4.rs b/rustlings/exercises/09_strings/strings4.rs deleted file mode 100644 index 3f7c5e7..0000000 --- a/rustlings/exercises/09_strings/strings4.rs +++ /dev/null @@ -1,37 +0,0 @@ -// Calls of this function should be replaced with calls of `string_slice` or `string`. -fn placeholder() {} - -fn string_slice(arg: &str) { - println!("{arg}"); -} - -fn string(arg: String) { - println!("{arg}"); -} - -// TODO: Here are a bunch of values - some are `String`, some are `&str`. -// Your task is to replace `placeholder(…)` with either `string_slice(…)` -// or `string(…)` depending on what you think each value is. -fn main() { - string_slice("blue"); - - string("red".to_string()); - - string(String::from("hi")); - - string("rust is fun!".to_owned()); - - string("nice weather".into()); - - string(format!("Interpolation {}", "Station")); - - // WARNING: This is byte indexing, not character indexing. - // Character indexing can be done using `s.chars().nth(INDEX)`. - string_slice(&String::from("abc")[0..1]); - - string_slice(" hello there ".trim()); - - string("Happy Monday!".replace("Mon", "Tues")); - - string("mY sHiFt KeY iS sTiCkY".to_lowercase()); -} diff --git a/rustlings/exercises/10_modules/README.md b/rustlings/exercises/10_modules/README.md deleted file mode 100644 index 3dc8a48..0000000 --- a/rustlings/exercises/10_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/rustlings/exercises/10_modules/modules1.rs b/rustlings/exercises/10_modules/modules1.rs deleted file mode 100644 index 0d7c5a2..0000000 --- a/rustlings/exercises/10_modules/modules1.rs +++ /dev/null @@ -1,15 +0,0 @@ -mod sausage_factory { - // Don't let anybody outside of this module see this! - fn get_secret_recipe() -> String { - String::from("Ginger") - } - - pub fn make_sausage() { - get_secret_recipe(); - println!("sausage!"); - } -} - -fn main() { - sausage_factory::make_sausage(); -} diff --git a/rustlings/exercises/10_modules/modules2.rs b/rustlings/exercises/10_modules/modules2.rs deleted file mode 100644 index 3cabbfd..0000000 --- a/rustlings/exercises/10_modules/modules2.rs +++ /dev/null @@ -1,26 +0,0 @@ -// You can bring module paths into scopes and provide new names for them with -// the `use` and `as` keywords. - -mod delicious_snacks { - // TODO: Add the following two `use` statements after fixing them. - pub use self::fruits::PEAR as fruit; - pub use self::veggies::CUCUMBER as veggie; - - mod fruits { - pub const PEAR: &str = "Pear"; - pub const APPLE: &str = "Apple"; - } - - mod veggies { - pub const CUCUMBER: &str = "Cucumber"; - pub const CARROT: &str = "Carrot"; - } -} - -fn main() { - println!( - "favorite snacks: {} and {}", - delicious_snacks::fruit, - delicious_snacks::veggie, - ); -} diff --git a/rustlings/exercises/10_modules/modules3.rs b/rustlings/exercises/10_modules/modules3.rs deleted file mode 100644 index 403b7ea..0000000 --- a/rustlings/exercises/10_modules/modules3.rs +++ /dev/null @@ -1,13 +0,0 @@ -// You can use the `use` keyword to bring module paths from modules from -// anywhere and especially from the standard library into your scope. - -// TODO: Bring `SystemTime` and `UNIX_EPOCH` from the `std::time` module into -// your scope. Bonus style points if you can do it with one line! -use std::time::{SystemTime, UNIX_EPOCH}; - -fn main() { - match SystemTime::now().duration_since(UNIX_EPOCH) { - Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), - Err(_) => panic!("SystemTime before UNIX EPOCH!"), - } -} diff --git a/rustlings/exercises/11_hashmaps/README.md b/rustlings/exercises/11_hashmaps/README.md deleted file mode 100644 index 80ec144..0000000 --- a/rustlings/exercises/11_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/rustlings/exercises/11_hashmaps/hashmaps1.rs b/rustlings/exercises/11_hashmaps/hashmaps1.rs deleted file mode 100644 index a746b32..0000000 --- a/rustlings/exercises/11_hashmaps/hashmaps1.rs +++ /dev/null @@ -1,43 +0,0 @@ -// 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 3 different -// types of fruits (e.g. apple, banana, mango) in the basket and the total count -// of all the fruits should be at least 5. - -use std::collections::HashMap; - -fn fruit_basket() -> HashMap { - // TODO: Declare the hash map. - let mut basket = HashMap::new(); - - // Two bananas are already given for you :) - basket.insert(String::from("banana"), 2); - - // TODO: Put more fruits in your basket. - basket.insert(String::from("banana"), 1); - basket.insert(String::from("orange"), 140000); - basket.insert(String::from("strawberry"), 5); - - basket -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/exercises/11_hashmaps/hashmaps2.rs b/rustlings/exercises/11_hashmaps/hashmaps2.rs deleted file mode 100644 index 482db7c..0000000 --- a/rustlings/exercises/11_hashmaps/hashmaps2.rs +++ /dev/null @@ -1,99 +0,0 @@ -// 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 the fruits that are already in the basket (Apple, -// Mango, and Lychee). - -use std::collections::HashMap; - -#[derive(Hash, PartialEq, Eq, Debug)] -enum Fruit { - Apple, - Banana, - Mango, - Lychee, - Pineapple, -} - -fn fruit_basket(basket: &mut HashMap) { - let fruit_kinds = [ - Fruit::Apple, - Fruit::Banana, - Fruit::Mango, - Fruit::Lychee, - Fruit::Pineapple, - ]; - - for fruit in fruit_kinds { - // This works just fine, but clippy doesn't like how readable and obvious the code is - // if !basket.contains_key(&fruit) { - // basket.insert(fruit, 10); - // } - basket.entry(fruit).or_insert(10); - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - // Don't modify this function! - fn get_fruit_basket() -> HashMap { - let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)]; - HashMap::from_iter(content) - } - - #[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 fruit_kinds = [ - Fruit::Apple, - Fruit::Banana, - Fruit::Mango, - Fruit::Lychee, - Fruit::Pineapple, - ]; - - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - - for fruit_kind in fruit_kinds { - let Some(amount) = basket.get(&fruit_kind) else { - panic!("Fruit kind {fruit_kind:?} was not found in basket"); - }; - assert!(*amount > 0); - } - } -} diff --git a/rustlings/exercises/11_hashmaps/hashmaps3.rs b/rustlings/exercises/11_hashmaps/hashmaps3.rs deleted file mode 100644 index 0fa4a6b..0000000 --- a/rustlings/exercises/11_hashmaps/hashmaps3.rs +++ /dev/null @@ -1,84 +0,0 @@ -// 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, the total -// number of goals the team scored, and the total number of goals the team -// conceded. - -use std::collections::HashMap; - -// A structure to store the goal details of a team. -#[derive(Default)] -struct TeamScores { - goals_scored: u8, - goals_conceded: u8, -} - -fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { - // The name of the team is the key and its associated struct is the value. - let mut scores = HashMap::<&str, TeamScores>::new(); - - for line in results.lines() { - let mut split_iterator = line.split(','); - // NOTE: We use `unwrap` because we didn't deal with error handling yet. - let team_1_name = split_iterator.next().unwrap(); - let team_2_name = split_iterator.next().unwrap(); - let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); - let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); - - // TODO: Populate the scores table with the extracted details. - // Keep in mind that goals scored by team 1 will be the number of goals - // conceded by team 2. Similarly, goals scored by team 2 will be the - // number of goals conceded by team 1. - let team_1 = scores.entry(team_1_name).or_default(); - team_1.goals_scored += team_1_score; - team_1.goals_conceded += team_2_score; - let team_2 = scores.entry(team_2_name).or_default(); - team_2.goals_scored += team_2_score; - team_2.goals_conceded += team_1_score; - - } - - scores -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - const RESULTS: &str = "England,France,4,2 -France,Italy,3,1 -Poland,Spain,2,0 -Germany,England,2,1 -England,Spain,1,0"; - - #[test] - fn build_scores() { - let scores = build_scores_table(RESULTS); - - assert!(["England", "France", "Germany", "Italy", "Poland", "Spain"] - .into_iter() - .all(|team_name| scores.contains_key(team_name))); - } - - #[test] - fn validate_team_score_1() { - let scores = build_scores_table(RESULTS); - let team = scores.get("England").unwrap(); - assert_eq!(team.goals_scored, 6); - assert_eq!(team.goals_conceded, 4); - } - - #[test] - fn validate_team_score_2() { - let scores = build_scores_table(RESULTS); - let team = scores.get("Spain").unwrap(); - assert_eq!(team.goals_scored, 0); - assert_eq!(team.goals_conceded, 3); - } -} diff --git a/rustlings/exercises/12_options/README.md b/rustlings/exercises/12_options/README.md deleted file mode 100644 index 624572a..0000000 --- a/rustlings/exercises/12_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/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/rustlings/exercises/12_options/options1.rs b/rustlings/exercises/12_options/options1.rs deleted file mode 100644 index be97952..0000000 --- a/rustlings/exercises/12_options/options1.rs +++ /dev/null @@ -1,42 +0,0 @@ -// This function returns how much ice cream there is left in the fridge. -// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, -// someone eats it all, so no ice cream is left (value 0). Return `None` if -// `hour_of_day` is higher than 23. -fn maybe_ice_cream(hour_of_day: u16) -> Option { - if hour_of_day >= 24 { - return None; - } - if hour_of_day >= 22 { - return Some(0); - } - Some(5) -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn raw_value() { - // TODO: Fix this test. How do you get the value contained in the - // Option? - let ice_creams = maybe_ice_cream(12).unwrap(); - - assert_eq!(ice_creams, 5); // Don't change this line. - } - - #[test] - fn check_ice_cream() { - assert_eq!(maybe_ice_cream(0), Some(5)); - assert_eq!(maybe_ice_cream(9), Some(5)); - assert_eq!(maybe_ice_cream(18), Some(5)); - assert_eq!(maybe_ice_cream(22), Some(0)); - assert_eq!(maybe_ice_cream(23), Some(0)); - assert_eq!(maybe_ice_cream(24), None); - assert_eq!(maybe_ice_cream(25), None); - } -} diff --git a/rustlings/exercises/12_options/options2.rs b/rustlings/exercises/12_options/options2.rs deleted file mode 100644 index 1039d61..0000000 --- a/rustlings/exercises/12_options/options2.rs +++ /dev/null @@ -1,39 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[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`. - if let Some(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 { - optional_integers.push(Some(i)); - } - - let mut cursor = range; - - // TODO: Make this a while-let statement. Remember that `Vec::pop()` - // adds another layer of `Option`. You can do nested pattern matching - // in if-let and while-let statements. - while let Some(Some(integer)) = optional_integers.pop() { - assert_eq!(integer, cursor); - cursor -= 1; - } - - assert_eq!(cursor, 0); - } -} diff --git a/rustlings/exercises/12_options/options3.rs b/rustlings/exercises/12_options/options3.rs deleted file mode 100644 index aecb7a5..0000000 --- a/rustlings/exercises/12_options/options3.rs +++ /dev/null @@ -1,17 +0,0 @@ -#[derive(Debug)] -struct Point { - x: i32, - y: i32, -} - -fn main() { - let optional_point = Some(Point { x: 100, y: 200 }); - - // TODO: Fix the compiler error by adding something to this match statement. - match optional_point { - Some(ref p) => println!("Coordinates are {},{}", p.x, p.y), - _ => panic!("No match!"), - } - - println!("{optional_point:?}"); // Don't change this line. -} diff --git a/rustlings/exercises/13_error_handling/README.md b/rustlings/exercises/13_error_handling/README.md deleted file mode 100644 index 9b6674b..0000000 --- a/rustlings/exercises/13_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/rustlings/exercises/13_error_handling/errors1.rs b/rustlings/exercises/13_error_handling/errors1.rs deleted file mode 100644 index b9b9bd5..0000000 --- a/rustlings/exercises/13_error_handling/errors1.rs +++ /dev/null @@ -1,40 +0,0 @@ -// TODO: 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 returning `None`. Thankfully, Rust has a similar -// construct to `Option` that can be used to express error conditions. Change -// the function signature and body to return `Result` instead -// of `Option`. -fn generate_nametag_text(name: String) -> Result { - if name.is_empty() { - Err(String::from("Empty names aren't allowed")) - } else { - Ok(format!("Hi! My name is {name}")) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generates_nametag_text_for_a_nonempty_name() { - assert_eq!( - generate_nametag_text("Beyoncé".to_string()).as_deref(), - Ok("Hi! My name is Beyoncé"), - ); - } - - #[test] - fn explains_why_generating_nametag_text_fails() { - assert_eq!( - generate_nametag_text(String::new()) - .as_ref() - .map_err(|e| e.as_str()), - Err("Empty names aren't allowed"), - ); - } -} diff --git a/rustlings/exercises/13_error_handling/errors2.rs b/rustlings/exercises/13_error_handling/errors2.rs deleted file mode 100644 index 3d850f7..0000000 --- a/rustlings/exercises/13_error_handling/errors2.rs +++ /dev/null @@ -1,50 +0,0 @@ -// 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, we get it as a string. They might have -// typed anything, not just numbers! -// -// Right now, this function isn't handling the error case at all. 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`. 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! - -use std::num::ParseIntError; - -fn total_cost(item_quantity: &str) -> Result { - let processing_fee = 1; - let cost_per_item = 5; - - // TODO: Handle the error case as described above. - let qty = item_quantity.parse::()?; - - Ok(qty * cost_per_item + processing_fee) -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - use std::num::IntErrorKind; - - #[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().kind(), - &IntErrorKind::InvalidDigit, - ); - } -} diff --git a/rustlings/exercises/13_error_handling/errors3.rs b/rustlings/exercises/13_error_handling/errors3.rs deleted file mode 100644 index bf21bbc..0000000 --- a/rustlings/exercises/13_error_handling/errors3.rs +++ /dev/null @@ -1,33 +0,0 @@ -// 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? - -use std::num::ParseIntError; - -// Don't change this function. -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) -} - -// TODO: Fix the compiler error by changing the signature and body of the -// `main` function. -fn main() -> Result<(), ParseIntError> { - let mut tokens = 100; - let pretend_user_input = "8"; - - // Don't change this line. - 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."); - } - - Ok(()) -} diff --git a/rustlings/exercises/13_error_handling/errors4.rs b/rustlings/exercises/13_error_handling/errors4.rs deleted file mode 100644 index e5f3d39..0000000 --- a/rustlings/exercises/13_error_handling/errors4.rs +++ /dev/null @@ -1,44 +0,0 @@ -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - // TODO: This function shouldn't always return an `Ok`. - // Read the tests below to clarify what should be returned. - if value < 0 { - return Err(CreationError::Negative); - } - if value == 0 { - return Err(CreationError::Zero); - } - Ok(Self(value as u64)) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_creation() { - assert_eq!( - PositiveNonzeroInteger::new(10), - Ok(PositiveNonzeroInteger(10)), - ); - assert_eq!( - PositiveNonzeroInteger::new(-10), - Err(CreationError::Negative), - ); - assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); - } -} diff --git a/rustlings/exercises/13_error_handling/errors5.rs b/rustlings/exercises/13_error_handling/errors5.rs deleted file mode 100644 index 405f0dc..0000000 --- a/rustlings/exercises/13_error_handling/errors5.rs +++ /dev/null @@ -1,56 +0,0 @@ -// This exercise is an altered version of the `errors4` exercise. It 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. -// -// 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`. - -use std::error::Error; -use std::fmt; - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -// This is required so that `CreationError` can implement `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 for CreationError {} - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - 0 => Err(CreationError::Zero), - x => Ok(PositiveNonzeroInteger(x as u64)), - } - } -} - -// TODO: Add the correct return type `Result<(), Box>`. What can we -// use to describe both errors? Is there a trait which both errors implement? -fn main() -> Result<(), Box> { - let pretend_user_input = "42"; - let x: i64 = pretend_user_input.parse()?; - println!("output={:?}", PositiveNonzeroInteger::new(x)?); - Ok(()) -} diff --git a/rustlings/exercises/13_error_handling/errors6.rs b/rustlings/exercises/13_error_handling/errors6.rs deleted file mode 100644 index 353b50b..0000000 --- a/rustlings/exercises/13_error_handling/errors6.rs +++ /dev/null @@ -1,91 +0,0 @@ -// 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. - -use std::num::ParseIntError; - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -// A custom error type that we will be using in `PositiveNonzeroInteger::parse`. -#[derive(PartialEq, Debug)] -enum ParsePosNonzeroError { - Creation(CreationError), - ParseInt(ParseIntError), -} - -impl ParsePosNonzeroError { - fn from_creation(err: CreationError) -> Self { - Self::Creation(err) - } - - // TODO: Add another error conversion function here. - fn from_parse_int(err: ParseIntError) -> Self { - Self::ParseInt(err) - } -} - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - 0 => Err(CreationError::Zero), - x => Ok(Self(x as u64)), - } - } - - fn parse(s: &str) -> Result { - // TODO: change this to return an appropriate error instead of panicking - // when `parse()` returns an error. - let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parse_int)?; - Self::new(x).map_err(ParsePosNonzeroError::from_creation) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_parse_error() { - assert!(matches!( - PositiveNonzeroInteger::parse("not a number"), - Err(ParsePosNonzeroError::ParseInt(_)), - )); - } - - #[test] - fn test_negative() { - assert_eq!( - PositiveNonzeroInteger::parse("-555"), - Err(ParsePosNonzeroError::Creation(CreationError::Negative)), - ); - } - - #[test] - fn test_zero() { - assert_eq!( - PositiveNonzeroInteger::parse("0"), - Err(ParsePosNonzeroError::Creation(CreationError::Zero)), - ); - } - - #[test] - fn test_positive() { - let x = PositiveNonzeroInteger::new(42).unwrap(); - assert_eq!(x.0, 42); - assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x)); - } -} diff --git a/rustlings/exercises/14_generics/README.md b/rustlings/exercises/14_generics/README.md deleted file mode 100644 index 0c8c8cb..0000000 --- a/rustlings/exercises/14_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 some rather involved 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/book/ch10-01-syntax.html) -- [Bounds](https://doc.rust-lang.org/rust-by-example/generics/bounds.html) diff --git a/rustlings/exercises/14_generics/generics1.rs b/rustlings/exercises/14_generics/generics1.rs deleted file mode 100644 index 7e5571f..0000000 --- a/rustlings/exercises/14_generics/generics1.rs +++ /dev/null @@ -1,18 +0,0 @@ -// `Vec` is generic over the type `T`. In most cases, the compiler is able to -// infer `T`, for example after pushing a value with a concrete type to the vector. -// But in this exercise, the compiler needs some help through a type annotation. - -fn main() { - // TODO: Fix the compiler error by annotating the type of the vector - // `Vec`. Choose `T` as some integer type that can be created from - // `u8` and `i8`. - let mut numbers: Vec = Vec::new(); - - // Don't change the lines below. - let n1: u8 = 42; - numbers.push(n1.into()); - let n2: i8 = -1; - numbers.push(n2.into()); - - println!("{numbers:?}"); -} diff --git a/rustlings/exercises/14_generics/generics2.rs b/rustlings/exercises/14_generics/generics2.rs deleted file mode 100644 index ba77625..0000000 --- a/rustlings/exercises/14_generics/generics2.rs +++ /dev/null @@ -1,31 +0,0 @@ -// This powerful wrapper provides the ability to store a positive integer value. -// TODO: Rewrite it using a generic so that it supports wrapping ANY type. -struct Wrapper { - value: T, -} - -// TODO: Adapt the struct's implementation to be generic over the wrapped value. -impl Wrapper { - fn new(value: T) -> Self { - Wrapper { value } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/exercises/15_traits/README.md b/rustlings/exercises/15_traits/README.md deleted file mode 100644 index ac87c64..0000000 --- a/rustlings/exercises/15_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/rustlings/exercises/15_traits/traits1.rs b/rustlings/exercises/15_traits/traits1.rs deleted file mode 100644 index fad6a50..0000000 --- a/rustlings/exercises/15_traits/traits1.rs +++ /dev/null @@ -1,33 +0,0 @@ -// The trait `AppendBar` has only one function which appends "Bar" to any object -// implementing this trait. -trait AppendBar { - fn append_bar(self) -> Self; -} - -impl AppendBar for String { - // TODO: Implement `AppendBar` for the type `String`. - fn append_bar(self) -> Self { - self + "Bar" - } -} - -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(), "FooBar"); - } - - #[test] - fn is_bar_bar() { - assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); - } -} diff --git a/rustlings/exercises/15_traits/traits2.rs b/rustlings/exercises/15_traits/traits2.rs deleted file mode 100644 index 5dfc36d..0000000 --- a/rustlings/exercises/15_traits/traits2.rs +++ /dev/null @@ -1,30 +0,0 @@ -trait AppendBar { - fn append_bar(self) -> Self; -} - -// TODO: Implement the trait `AppendBar` for a vector of strings. -// `append_bar` should push the string "Bar" into the vector. - -impl AppendBar for Vec { - fn append_bar(self) -> Self { - let mut s = self.clone(); - s.push(String::from("Bar")); - s - } -} - -fn main() { - // You can optionally experiment here. -} - -#[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(), "Bar"); - assert_eq!(foo.pop().unwrap(), "Foo"); - } -} diff --git a/rustlings/exercises/15_traits/traits3.rs b/rustlings/exercises/15_traits/traits3.rs deleted file mode 100644 index 144ac0a..0000000 --- a/rustlings/exercises/15_traits/traits3.rs +++ /dev/null @@ -1,40 +0,0 @@ -trait Licensed { - // TODO: Add a default implementation for `licensing_info` so that - // implementors like the two structs below can share that default behavior - // without repeating the function. - // The default license information should be the string "Default license". - fn licensing_info(&self) -> String { - String::from("Default license") - } -} - -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. - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_licensing_info_the_same() { - let licensing_info = "Default license"; - 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/rustlings/exercises/15_traits/traits4.rs b/rustlings/exercises/15_traits/traits4.rs deleted file mode 100644 index b23dcdd..0000000 --- a/rustlings/exercises/15_traits/traits4.rs +++ /dev/null @@ -1,35 +0,0 @@ -trait Licensed { - fn licensing_info(&self) -> String { - "Default license".to_string() - } -} - -struct SomeSoftware; -struct OtherSoftware; - -impl Licensed for SomeSoftware {} -impl Licensed for OtherSoftware {} - -// TODO: Fix the compiler error by only changing the signature of this function. -fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool { - software1.licensing_info() == software2.licensing_info() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compare_license_information() { - assert!(compare_license_types(SomeSoftware, OtherSoftware)); - } - - #[test] - fn compare_license_information_backwards() { - assert!(compare_license_types(OtherSoftware, SomeSoftware)); - } -} diff --git a/rustlings/exercises/15_traits/traits5.rs b/rustlings/exercises/15_traits/traits5.rs deleted file mode 100644 index 6548014..0000000 --- a/rustlings/exercises/15_traits/traits5.rs +++ /dev/null @@ -1,39 +0,0 @@ -trait SomeTrait { - fn some_function(&self) -> bool { - true - } -} - -trait OtherTrait { - fn other_function(&self) -> bool { - true - } -} - -struct SomeStruct; -impl SomeTrait for SomeStruct {} -impl OtherTrait for SomeStruct {} - -struct OtherStruct; -impl SomeTrait for OtherStruct {} -impl OtherTrait for OtherStruct {} - -// TODO: Fix the compiler error by only changing the signature of this function. -fn some_func(item: T) -> bool { - item.some_function() && item.other_function() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_some_func() { - assert!(some_func(SomeStruct)); - assert!(some_func(OtherStruct)); - } -} diff --git a/rustlings/exercises/16_lifetimes/README.md b/rustlings/exercises/16_lifetimes/README.md deleted file mode 100644 index 91373f7..0000000 --- a/rustlings/exercises/16_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/rustlings/exercises/16_lifetimes/lifetimes1.rs b/rustlings/exercises/16_lifetimes/lifetimes1.rs deleted file mode 100644 index 683bd75..0000000 --- a/rustlings/exercises/16_lifetimes/lifetimes1.rs +++ /dev/null @@ -1,28 +0,0 @@ -// 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? - -// TODO: Fix the compiler error by updating the function signature. -fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { - if x.len() > y.len() { - x - } else { - y - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_longest() { - assert_eq!(longest("abcd", "123"), "abcd"); - assert_eq!(longest("abc", "1234"), "1234"); - } -} diff --git a/rustlings/exercises/16_lifetimes/lifetimes2.rs b/rustlings/exercises/16_lifetimes/lifetimes2.rs deleted file mode 100644 index ebbc99c..0000000 --- a/rustlings/exercises/16_lifetimes/lifetimes2.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Don't change this function. -fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { - if x.len() > y.len() { - x - } else { - y - } -} - -fn main() { - // TODO: Fix the compiler error by moving one line. - - let string1 = String::from("long string is long"); - let string2 = String::from("xyz"); - let result; - { - result = longest(&string1, &string2); - } - println!("The longest string is '{result}'"); -} diff --git a/rustlings/exercises/16_lifetimes/lifetimes3.rs b/rustlings/exercises/16_lifetimes/lifetimes3.rs deleted file mode 100644 index 91e3922..0000000 --- a/rustlings/exercises/16_lifetimes/lifetimes3.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Lifetimes are also needed when structs hold references. - -// TODO: Fix the compiler errors about the struct. -struct Book<'a> { - author: &'a str, - title: &'a str, -} - -fn main() { - let book = Book { - author: "George Orwell", - title: "1984", - }; - - println!("{} by {}", book.title, book.author); -} diff --git a/rustlings/exercises/17_tests/README.md b/rustlings/exercises/17_tests/README.md deleted file mode 100644 index 27c6818..0000000 --- a/rustlings/exercises/17_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/rustlings/exercises/17_tests/tests1.rs b/rustlings/exercises/17_tests/tests1.rs deleted file mode 100644 index 7fd7e10..0000000 --- a/rustlings/exercises/17_tests/tests1.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Tests are important to ensure that your code does what you think it should -// do. - -fn is_even(n: i64) -> bool { - n % 2 == 0 -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - // TODO: Import `is_even`. You can use a wildcard to import everything in - // the outer module. - use super::*; - - #[test] - fn you_can_assert() { - // TODO: Test the function `is_even` with some values. - assert!(is_even(2)); - assert!(!is_even(3)); - } -} diff --git a/rustlings/exercises/17_tests/tests2.rs b/rustlings/exercises/17_tests/tests2.rs deleted file mode 100644 index 16bf0fa..0000000 --- a/rustlings/exercises/17_tests/tests2.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Calculates the power of 2 using a bit shift. -// `1 << n` is equivalent to "2 to the power of n". -fn power_of_2(n: u8) -> u64 { - 1 << n -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn you_can_assert_eq() { - // TODO: Test the function `power_of_2` with some values. - assert_eq!(power_of_2(1), 2); - assert_eq!(power_of_2(2), 4); - assert_eq!(power_of_2(3), 8); - assert_eq!(power_of_2(4), 16); - } -} diff --git a/rustlings/exercises/17_tests/tests3.rs b/rustlings/exercises/17_tests/tests3.rs deleted file mode 100644 index 085bb62..0000000 --- a/rustlings/exercises/17_tests/tests3.rs +++ /dev/null @@ -1,51 +0,0 @@ -struct Rectangle { - width: i32, - height: i32, -} - -impl Rectangle { - // Don't change this function. - fn new(width: i32, height: i32) -> Self { - if width <= 0 || height <= 0 { - // Returning a `Result` would be better here. But we want to learn - // how to test functions that can panic. - panic!("Rectangle width and height must be positive"); - } - - Rectangle { width, height } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn correct_width_and_height() { - // TODO: This test should check if the rectangle has the size that we - // pass to its constructor. - let rect = Rectangle::new(10, 20); - assert_eq!(rect.width, 10); // Check width - assert_eq!(rect.height, 20); // Check height - } - - // TODO: This test should check if the program panics when we try to create - // a rectangle with negative width. - #[test] - #[should_panic] - fn negative_width() { - let _rect = Rectangle::new(-10, 10); - } - - // TODO: This test should check if the program panics when we try to create - // a rectangle with negative height. - #[test] - #[should_panic] - fn negative_height() { - let _rect = Rectangle::new(10, -10); - } -} diff --git a/rustlings/exercises/18_iterators/README.md b/rustlings/exercises/18_iterators/README.md deleted file mode 100644 index 0e8b671..0000000 --- a/rustlings/exercises/18_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/rustlings/exercises/18_iterators/iterators1.rs b/rustlings/exercises/18_iterators/iterators1.rs deleted file mode 100644 index 71d8112..0000000 --- a/rustlings/exercises/18_iterators/iterators1.rs +++ /dev/null @@ -1,25 +0,0 @@ -// 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. - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn iterators() { - let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"]; - - // TODO: Create an iterator over the array. - let mut fav_fruits_iterator = my_fav_fruits.iter(); - - assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); - assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); // TODO: Replace `todo!()` - assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); - assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); // TODO: Replace `todo!()` - assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); - assert_eq!(fav_fruits_iterator.next(), None); // TODO: Replace `todo!()` - } -} diff --git a/rustlings/exercises/18_iterators/iterators2.rs b/rustlings/exercises/18_iterators/iterators2.rs deleted file mode 100644 index c827529..0000000 --- a/rustlings/exercises/18_iterators/iterators2.rs +++ /dev/null @@ -1,63 +0,0 @@ -// In this exercise, you'll learn some of the unique advantages that iterators -// can offer. - -// TODO: Complete the `capitalize_first` function. -// "hello" -> "Hello" -fn capitalize_first(input: &str) -> String { - let mut chars = input.chars(); - match chars.next() { - None => String::new(), - Some(first) => first.to_uppercase().to_string() + &input[1..], - } -} - -// TODO: Apply the `capitalize_first` function to a slice of string slices. -// Return a vector of strings. -// ["hello", "world"] -> ["Hello", "World"] -fn capitalize_words_vector(words: &[&str]) -> Vec { - let mut v = Vec::new(); - for word in words { - if !word.trim().is_empty() { - v.push(capitalize_first(word)); - } - } - v -} - -// TODO: Apply the `capitalize_first` function again to a slice of string -// slices. Return a single string. -// ["hello", " ", "world"] -> "Hello World" -fn capitalize_words_string(words: &[&str]) -> String { - capitalize_words_vector(words).join(" ") -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/exercises/18_iterators/iterators3.rs b/rustlings/exercises/18_iterators/iterators3.rs deleted file mode 100644 index 919739b..0000000 --- a/rustlings/exercises/18_iterators/iterators3.rs +++ /dev/null @@ -1,84 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -enum DivisionError { - // Example: 42 / 0 - DivideByZero, - // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1` - IntegerOverflow, - // Example: 5 / 2 = 2.5 - NotDivisible, -} - -// TODO: Calculate `a` divided by `b` if `a` is evenly divisible by `b`. -// Otherwise, return a suitable error. -fn divide(a: i64, b: i64) -> Result { - if b == 0 { - return Err(DivisionError::DivideByZero); - } - if a == i64::MIN && b == -1 { - return Err(DivisionError::IntegerOverflow); - } - if a % b != 0 { - return Err(DivisionError::NotDivisible); - } - Ok(a / b) -} - -// TODO: Add the correct return type and complete the function body. -// Desired output: `Ok([1, 11, 1426, 3])` -fn result_with_list() -> Result, DivisionError> { - let numbers = [27, 297, 38502, 81]; - numbers.into_iter().map(|n| divide(n, 27)).collect() -} - -// TODO: Add the correct return type and complete the function body. -// Desired output: `[Ok(1), Ok(11), Ok(1426), Ok(3)]` -fn list_of_results() -> Vec> { - let numbers = [27, 297, 38502, 81]; - numbers.into_iter().map(|n| divide(n, 27)).collect() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_success() { - assert_eq!(divide(81, 9), Ok(9)); - assert_eq!(divide(81, -1), Ok(-81)); - assert_eq!(divide(i64::MIN, i64::MIN), Ok(1)); - } - - #[test] - fn test_divide_by_0() { - assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); - } - - #[test] - fn test_integer_overflow() { - assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow)); - } - - #[test] - fn test_not_divisible() { - assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); - } - - #[test] - fn test_divide_0_by_something() { - assert_eq!(divide(0, 81), Ok(0)); - } - - #[test] - fn test_result_with_list() { - assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]); - } - - #[test] - fn test_list_of_results() { - assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]); - } -} diff --git a/rustlings/exercises/18_iterators/iterators4.rs b/rustlings/exercises/18_iterators/iterators4.rs deleted file mode 100644 index f153786..0000000 --- a/rustlings/exercises/18_iterators/iterators4.rs +++ /dev/null @@ -1,42 +0,0 @@ -fn factorial(num: u64) -> u64 { - // TODO: Complete this function to return the factorial of `num` which is - // defined as `1 * 2 * 3 * … * num`. - // https://en.wikipedia.org/wiki/Factorial - // - // Do not use: - // - early returns (using the `return` keyword explicitly) - // Try not to use: - // - imperative style loops (for/while) - // - additional variables - // For an extra challenge, don't use: - // - recursion - (1..=num).reduce(|a, b| a * b).unwrap_or(1) -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn factorial_of_0() { - assert_eq!(factorial(0), 1); - } - - #[test] - fn factorial_of_1() { - assert_eq!(factorial(1), 1); - } - #[test] - fn factorial_of_2() { - assert_eq!(factorial(2), 2); - } - - #[test] - fn factorial_of_4() { - assert_eq!(factorial(4), 24); - } -} diff --git a/rustlings/exercises/18_iterators/iterators5.rs b/rustlings/exercises/18_iterators/iterators5.rs deleted file mode 100644 index 74f1c74..0000000 --- a/rustlings/exercises/18_iterators/iterators5.rs +++ /dev/null @@ -1,155 +0,0 @@ -// 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 to not use imperative loops (for/while). - -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 -} - -// TODO: Implement the functionality of `count_for` but with an iterator instead -// of a `for` loop. -fn count_iterator(map: &HashMap, value: Progress) -> usize { - map.values().filter(|&&x| x == value).count() - // `map` is a hash map with `String` keys and `Progress` values. - // map = { "variables1": Complete, "from_str": None, … } -} - -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 -} - -// TODO: Implement the functionality of `count_collection_for` but with an -// iterator instead of a `for` loop. -fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { - collection.iter().map(|m| count_iterator(m, value)).sum() - // `collection` is a slice of hash maps. - // collection = [{ "variables1": Complete, "from_str": None, … }, - // { "variables2": Complete, … }, … ] -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - 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] - } - - #[test] - fn count_complete() { - let map = get_map(); - assert_eq!(count_iterator(&map, Progress::Complete), 3); - } - - #[test] - fn count_some() { - let map = get_map(); - assert_eq!(count_iterator(&map, Progress::Some), 1); - } - - #[test] - fn count_none() { - let map = get_map(); - assert_eq!(count_iterator(&map, Progress::None), 2); - } - - #[test] - fn count_complete_equals_for() { - let map = get_map(); - let progress_states = [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!( - count_collection_iterator(&collection, Progress::Complete), - 6, - ); - } - - #[test] - fn count_collection_some() { - let collection = get_vec_map(); - assert_eq!(count_collection_iterator(&collection, Progress::Some), 1); - } - - #[test] - fn count_collection_none() { - let collection = get_vec_map(); - assert_eq!(count_collection_iterator(&collection, Progress::None), 4); - } - - #[test] - fn count_collection_equals_for() { - let collection = get_vec_map(); - let progress_states = [Progress::Complete, Progress::Some, Progress::None]; - - for progress_state in progress_states { - assert_eq!( - count_collection_for(&collection, progress_state), - count_collection_iterator(&collection, progress_state), - ); - } - } -} diff --git a/rustlings/exercises/19_smart_pointers/README.md b/rustlings/exercises/19_smart_pointers/README.md deleted file mode 100644 index d56d2b6..0000000 --- a/rustlings/exercises/19_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/rustlings/exercises/19_smart_pointers/arc1.rs b/rustlings/exercises/19_smart_pointers/arc1.rs deleted file mode 100644 index f44e4e1..0000000 --- a/rustlings/exercises/19_smart_pointers/arc1.rs +++ /dev/null @@ -1,45 +0,0 @@ -// In this exercise, we are given a `Vec` of `u32` called `numbers` with values -// ranging from 0 to 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, … -// -// Each thread should own a reference-counting pointer to the vector of -// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`. -// -// Don't get distracted by how threads are spawned and joined. We will practice -// that later in the exercises about threads. - -// Don't change the lines below. -#![forbid(unused_imports)] -use std::{sync::Arc, thread}; - -fn main() { - let numbers: Vec<_> = (0..100u32).collect(); - - // TODO: Define `shared_numbers` by using `Arc`. - let shared_numbers = Arc::new(numbers); - - let mut join_handles = Vec::new(); - - for offset in 0..8 { - // TODO: Define `child_numbers` using `shared_numbers`. - let child_numbers = shared_numbers.clone(); - - let handle = thread::spawn(move || { - let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); - println!("Sum of offset {offset} is {sum}"); - }); - - join_handles.push(handle); - } - - for handle in join_handles.into_iter() { - handle.join().unwrap(); - } -} diff --git a/rustlings/exercises/19_smart_pointers/box1.rs b/rustlings/exercises/19_smart_pointers/box1.rs deleted file mode 100644 index ee379ca..0000000 --- a/rustlings/exercises/19_smart_pointers/box1.rs +++ /dev/null @@ -1,50 +0,0 @@ -// 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`. - -// TODO: Use a `Box` in the enum definition to make the code compile. -#[derive(PartialEq, Debug)] -enum List { - Cons(i32, Box), - Nil, -} - -// TODO: Create an empty cons list. -fn create_empty_list() -> List { - List::Nil -} - -// TODO: Create a non-empty cons list. -fn create_non_empty_list() -> List { - List::Cons(1, Box::new(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(), - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_create_empty_list() { - assert_eq!(create_empty_list(), List::Nil); - } - - #[test] - fn test_create_non_empty_list() { - assert_ne!(create_empty_list(), create_non_empty_list()); - } -} diff --git a/rustlings/exercises/19_smart_pointers/cow1.rs b/rustlings/exercises/19_smart_pointers/cow1.rs deleted file mode 100644 index 56a25b9..0000000 --- a/rustlings/exercises/19_smart_pointers/cow1.rs +++ /dev/null @@ -1,66 +0,0 @@ -// This exercise explores the `Cow` (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. - -use std::borrow::Cow; - -fn abs_all(input: &mut Cow<[i32]>) { - for ind in 0..input.len() { - let value = input[ind]; - if value < 0 { - // Clones into a vector if not already owned. - input.to_mut()[ind] = -value; - } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference_mutation() { - // Clone occurs because `input` needs to be mutated. - let vec = vec![-1, 0, 1]; - let mut input = Cow::from(&vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Owned(_))); - } - - #[test] - fn reference_no_mutation() { - // No clone occurs because `input` doesn't need to be mutated. - let vec = vec![0, 1, 2]; - let mut input = Cow::from(&vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Borrowed(_))); - } - - #[test] - fn owned_no_mutation() { - // We can also pass `vec` without `&` so `Cow` owns it directly. In this - // case, no mutation occurs (all numbers are already absolute) and thus - // also no clone. But the result is still owned because it was never - // borrowed or mutated. - let vec = vec![0, 1, 2]; - let mut input = Cow::from(vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Owned(_))); - } - - #[test] - fn owned_mutation() { - // Of course this is also the case if a mutation does occur (not all - // numbers are absolute). In this case, the call to `to_mut()` in the - // `abs_all` function returns a reference to the same data as before. - let vec = vec![-1, 0, 1]; - let mut input = Cow::from(vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Owned(_))); - } -} diff --git a/rustlings/exercises/19_smart_pointers/rc1.rs b/rustlings/exercises/19_smart_pointers/rc1.rs deleted file mode 100644 index 5c9ce84..0000000 --- a/rustlings/exercises/19_smart_pointers/rc1.rs +++ /dev/null @@ -1,108 +0,0 @@ -// 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 `Planet`s. The planets take ownership of the sun, indicating that -// they revolve around the sun. - -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:?}!"); - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rc1() { - 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::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 7 references - saturn.details(); - - // TODO - let uranus = Planet::Uranus(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 8 references - uranus.details(); - - // TODO - let neptune = Planet::Neptune(Rc::clone(&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 - drop(earth); - println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - - // TODO - drop(venus); - println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - - // TODO - drop(mercury); - println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference - - assert_eq!(Rc::strong_count(&sun), 1); - } -} diff --git a/rustlings/exercises/20_threads/README.md b/rustlings/exercises/20_threads/README.md deleted file mode 100644 index 0b32fb1..0000000 --- a/rustlings/exercises/20_threads/README.md +++ /dev/null @@ -1,10 +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) -- [Using Message Passing to Transfer Data Between Threads](https://doc.rust-lang.org/book/ch16-02-message-passing.html) diff --git a/rustlings/exercises/20_threads/threads1.rs b/rustlings/exercises/20_threads/threads1.rs deleted file mode 100644 index dbc64b1..0000000 --- a/rustlings/exercises/20_threads/threads1.rs +++ /dev/null @@ -1,37 +0,0 @@ -// This program spawns multiple threads that each runs for at least 250ms, and -// each thread returns how much time it took to complete. The program should -// wait until all the spawned threads have finished and should collect their -// return values into a vector. - -use std::{ - thread, - time::{Duration, Instant}, -}; - -fn main() { - let mut handles = Vec::new(); - for i in 0..10 { - let handle = thread::spawn(move || { - let start = Instant::now(); - thread::sleep(Duration::from_millis(250)); - println!("Thread {i} done"); - start.elapsed().as_millis() - }); - handles.push(handle); - } - - let mut results = Vec::new(); - for handle in handles { - // TODO: Collect the results of all threads into the `results` vector. - // Use the `JoinHandle` struct which is returned by `thread::spawn`. - } - - if results.len() != 10 { - panic!("Oh no! Some thread isn't done yet!"); - } - - println!(); - for (i, result) in results.into_iter().enumerate() { - println!("Thread {i} took {result}ms"); - } -} diff --git a/rustlings/exercises/20_threads/threads2.rs b/rustlings/exercises/20_threads/threads2.rs deleted file mode 100644 index 7020cb9..0000000 --- a/rustlings/exercises/20_threads/threads2.rs +++ /dev/null @@ -1,34 +0,0 @@ -// 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_done` - -use std::{sync::Arc, thread, time::Duration}; - -struct JobStatus { - jobs_done: u32, -} - -fn main() { - // TODO: `Arc` isn't enough if you want a **mutable** shared state. - let status = Arc::new(JobStatus { jobs_done: 0 }); - - let mut handles = Vec::new(); - 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_done += 1; - }); - handles.push(handle); - } - - // Waiting for all jobs to complete. - for handle in handles { - handle.join().unwrap(); - } - - // TODO: Print the value of `JobStatus.jobs_done`. - println!("Jobs done: {}", todo!()); -} diff --git a/rustlings/exercises/20_threads/threads3.rs b/rustlings/exercises/20_threads/threads3.rs deleted file mode 100644 index 6d16bd9..0000000 --- a/rustlings/exercises/20_threads/threads3.rs +++ /dev/null @@ -1,60 +0,0 @@ -use std::{sync::mpsc, thread, time::Duration}; - -struct Queue { - first_half: Vec, - second_half: Vec, -} - -impl Queue { - fn new() -> Self { - Self { - first_half: vec![1, 2, 3, 4, 5], - second_half: vec![6, 7, 8, 9, 10], - } - } -} - -fn send_tx(q: Queue, tx: mpsc::Sender) { - // TODO: We want to send `tx` to both threads. But currently, it is moved - // into the first thread. How could you solve this problem? - thread::spawn(move || { - for val in q.first_half { - println!("Sending {val:?}"); - tx.send(val).unwrap(); - thread::sleep(Duration::from_millis(250)); - } - }); - - thread::spawn(move || { - for val in q.second_half { - println!("Sending {val:?}"); - tx.send(val).unwrap(); - thread::sleep(Duration::from_millis(250)); - } - }); -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn threads3() { - let (tx, rx) = mpsc::channel(); - let queue = Queue::new(); - - send_tx(queue, tx); - - let mut received = Vec::with_capacity(10); - for value in rx { - received.push(value); - } - - received.sort(); - assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); - } -} diff --git a/rustlings/exercises/21_macros/README.md b/rustlings/exercises/21_macros/README.md deleted file mode 100644 index de7fb7b..0000000 --- a/rustlings/exercises/21_macros/README.md +++ /dev/null @@ -1,15 +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 - -- [The Rust Book - Macros](https://doc.rust-lang.org/book/ch20-05-macros.html) -- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) -- [Rust by Example - macro_rules!](https://doc.rust-lang.org/rust-by-example/macros.html) diff --git a/rustlings/exercises/21_macros/macros1.rs b/rustlings/exercises/21_macros/macros1.rs deleted file mode 100644 index fb3c3ff..0000000 --- a/rustlings/exercises/21_macros/macros1.rs +++ /dev/null @@ -1,10 +0,0 @@ -macro_rules! my_macro { - () => { - println!("Check out my macro!"); - }; -} - -fn main() { - // TODO: Fix the macro call. - my_macro(); -} diff --git a/rustlings/exercises/21_macros/macros2.rs b/rustlings/exercises/21_macros/macros2.rs deleted file mode 100644 index 2d9dec7..0000000 --- a/rustlings/exercises/21_macros/macros2.rs +++ /dev/null @@ -1,10 +0,0 @@ -fn main() { - my_macro!(); -} - -// TODO: Fix the compiler error by moving the whole definition of this macro. -macro_rules! my_macro { - () => { - println!("Check out my macro!"); - }; -} diff --git a/rustlings/exercises/21_macros/macros3.rs b/rustlings/exercises/21_macros/macros3.rs deleted file mode 100644 index 9537494..0000000 --- a/rustlings/exercises/21_macros/macros3.rs +++ /dev/null @@ -1,13 +0,0 @@ -// TODO: Fix the compiler error without taking the macro definition out of this -// module. -mod macros { - macro_rules! my_macro { - () => { - println!("Check out my macro!"); - }; - } -} - -fn main() { - my_macro!(); -} diff --git a/rustlings/exercises/21_macros/macros4.rs b/rustlings/exercises/21_macros/macros4.rs deleted file mode 100644 index 9d77f6a..0000000 --- a/rustlings/exercises/21_macros/macros4.rs +++ /dev/null @@ -1,15 +0,0 @@ -// TODO: Fix the compiler error by adding one or two characters. -#[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/rustlings/exercises/22_clippy/README.md b/rustlings/exercises/22_clippy/README.md deleted file mode 100644 index 55438af..0000000 --- a/rustlings/exercises/22_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/rustlings/exercises/22_clippy/clippy1.rs b/rustlings/exercises/22_clippy/clippy1.rs deleted file mode 100644 index 7165da4..0000000 --- a/rustlings/exercises/22_clippy/clippy1.rs +++ /dev/null @@ -1,15 +0,0 @@ -// 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. - -fn main() { - // TODO: Fix the Clippy lint in this line. - let pi = 3.14; - let radius: f32 = 5.0; - - let area = pi * radius.powi(2); - - println!("The area of a circle with radius {radius:.2} is {area:.5}"); -} diff --git a/rustlings/exercises/22_clippy/clippy2.rs b/rustlings/exercises/22_clippy/clippy2.rs deleted file mode 100644 index 8cfe6f8..0000000 --- a/rustlings/exercises/22_clippy/clippy2.rs +++ /dev/null @@ -1,10 +0,0 @@ -fn main() { - let mut res = 42; - let option = Some(12); - // TODO: Fix the Clippy lint. - for x in option { - res += x; - } - - println!("{res}"); -} diff --git a/rustlings/exercises/22_clippy/clippy3.rs b/rustlings/exercises/22_clippy/clippy3.rs deleted file mode 100644 index 7a3cb39..0000000 --- a/rustlings/exercises/22_clippy/clippy3.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Here are some more easy Clippy fixes so you can see its utility 📎 -// TODO: Fix all the Clippy lints. - -#[rustfmt::skip] -#[allow(unused_variables, unused_assignments)] -fn main() { - let my_option: Option<&str> = None; - // Assume that you don't know the value of `my_option`. - // In the case of `Some`, we want to print its value. - if my_option.is_none() { - println!("{}", 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_a}; value b: {value_b}"); -} diff --git a/rustlings/exercises/23_conversions/README.md b/rustlings/exercises/23_conversions/README.md deleted file mode 100644 index 619a78c..0000000 --- a/rustlings/exercises/23_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/rustlings/exercises/23_conversions/as_ref_mut.rs b/rustlings/exercises/23_conversions/as_ref_mut.rs deleted file mode 100644 index d7892dd..0000000 --- a/rustlings/exercises/23_conversions/as_ref_mut.rs +++ /dev/null @@ -1,62 +0,0 @@ -// 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. - -// Obtain the number of bytes (not characters) in the given argument -// (`.len()` returns the number of bytes in a string). -// TODO: Add the `AsRef` trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { - arg.as_ref().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. -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/exercises/23_conversions/from_into.rs b/rustlings/exercises/23_conversions/from_into.rs deleted file mode 100644 index bc2783a..0000000 --- a/rustlings/exercises/23_conversions/from_into.rs +++ /dev/null @@ -1,130 +0,0 @@ -// The `From` trait is used for value-to-value conversions. If `From` is -// implemented, an implementation of `Into` is automatically provided. -// You can read more about it in the documentation: -// https://doc.rust-lang.org/std/convert/trait.From.html - -#[derive(Debug)] -struct Person { - name: String, - age: u8, -} - -// 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() -> Self { - Self { - name: String::from("John"), - age: 30, - } - } -} - -// TODO: Complete this `From` implementation to be able to parse a `Person` -// out of a string in the form of "Mark,20". -// Note that you'll need to parse the age component into a `u8` with something -// like `"4".parse::()`. -// -// Steps: -// 1. Split the given string on the commas present in it. -// 2. If the split operation returns less or more than 2 elements, return the -// default of `Person`. -// 3. Use the first element from the split operation as the name. -// 4. If the name is empty, return the default of `Person`. -// 5. Parse the second element from the split operation into a `u8` as the age. -// 6. If parsing the age fails, return the default of `Person`. -impl From<&str> for Person { - fn from(s: &str) -> Self {} -} - -fn main() { - // Use the `from` function. - let p1 = Person::from("Mark,20"); - println!("{p1:?}"); - - // Since `From` is implemented for Person, we are able to use `Into`. - let p2: Person = "Gerald,70".into(); - println!("{p2:?}"); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_default() { - let dp = Person::default(); - assert_eq!(dp.name, "John"); - assert_eq!(dp.age, 30); - } - - #[test] - fn test_bad_convert() { - let p = Person::from(""); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_good_convert() { - let p = Person::from("Mark,20"); - assert_eq!(p.name, "Mark"); - assert_eq!(p.age, 20); - } - - #[test] - fn test_bad_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, "John"); - assert_eq!(p.age, 30); - } - - #[test] - fn test_trailing_comma_and_some_string() { - let p: Person = Person::from("Mike,32,dog"); - assert_eq!(p.name, "John"); - assert_eq!(p.age, 30); - } -} diff --git a/rustlings/exercises/23_conversions/from_str.rs b/rustlings/exercises/23_conversions/from_str.rs deleted file mode 100644 index ec6d3fd..0000000 --- a/rustlings/exercises/23_conversions/from_str.rs +++ /dev/null @@ -1,113 +0,0 @@ -// This is similar to the previous `from_into` exercise. 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 in the documentation: -// https://doc.rust-lang.org/std/str/trait.FromStr.html - -use std::num::ParseIntError; -use std::str::FromStr; - -#[derive(Debug, PartialEq)] -struct Person { - name: String, - age: u8, -} - -// We will use this error type for the `FromStr` implementation. -#[derive(Debug, PartialEq)] -enum ParsePersonError { - // Incorrect number of fields - BadLen, - // Empty name field - NoName, - // Wrapped error from parse::() - ParseInt(ParseIntError), -} - -// TODO: Complete this `FromStr` implementation to be able to parse a `Person` -// out of a string in the form of "Mark,20". -// Note that you'll need to parse the age component into a `u8` with something -// like `"4".parse::()`. -// -// Steps: -// 1. Split the given string on the commas present in it. -// 2. If the split operation returns less or more than 2 elements, return the -// error `ParsePersonError::BadLen`. -// 3. Use the first element from the split operation as the name. -// 4. If the name is empty, return the error `ParsePersonError::NoName`. -// 5. Parse the second element from the split operation into a `u8` as the age. -// 6. If parsing the age fails, return the error `ParsePersonError::ParseInt`. -impl FromStr for Person { - type Err = ParsePersonError; - - fn from_str(s: &str) -> Result {} -} - -fn main() { - let p = "Mark,20".parse::(); - println!("{p:?}"); -} - -#[cfg(test)] -mod tests { - use super::*; - use ParsePersonError::*; - - #[test] - fn empty_input() { - assert_eq!("".parse::(), Err(BadLen)); - } - - #[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(ParseInt(_)))); - } - - #[test] - fn invalid_age() { - assert!(matches!("John,twenty".parse::(), Err(ParseInt(_)))); - } - - #[test] - fn missing_comma_and_age() { - assert_eq!("John".parse::(), Err(BadLen)); - } - - #[test] - fn missing_name() { - assert_eq!(",1".parse::(), Err(NoName)); - } - - #[test] - fn missing_name_and_age() { - assert!(matches!(",".parse::(), Err(NoName | ParseInt(_)))); - } - - #[test] - fn missing_name_and_invalid_age() { - assert!(matches!( - ",one".parse::(), - Err(NoName | ParseInt(_)), - )); - } - - #[test] - fn trailing_comma() { - assert_eq!("John,32,".parse::(), Err(BadLen)); - } - - #[test] - fn trailing_comma_and_some_string() { - assert_eq!("John,32,man".parse::(), Err(BadLen)); - } -} diff --git a/rustlings/exercises/23_conversions/try_from_into.rs b/rustlings/exercises/23_conversions/try_from_into.rs deleted file mode 100644 index f3ae80a..0000000 --- a/rustlings/exercises/23_conversions/try_from_into.rs +++ /dev/null @@ -1,177 +0,0 @@ -// `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 in the documentation: -// https://doc.rust-lang.org/std/convert/trait.TryFrom.html - -#![allow(clippy::useless_vec)] -use std::convert::{TryFrom, TryInto}; - -#[derive(Debug, PartialEq)] -struct Color { - red: u8, - green: u8, - blue: u8, -} - -// We will use this error type for the `TryFrom` conversions. -#[derive(Debug, PartialEq)] -enum IntoColorError { - // Incorrect length of slice - BadLen, - // Integer conversion error - IntConversion, -} - -// TODO: Tuple implementation. -// Correct RGB color values must be integers in the 0..=255 range. -impl TryFrom<(i16, i16, i16)> for Color { - type Error = IntoColorError; - - fn try_from(tuple: (i16, i16, i16)) -> Result {} -} - -// TODO: Array implementation. -impl TryFrom<[i16; 3]> for Color { - type Error = IntoColorError; - - fn try_from(arr: [i16; 3]) -> Result {} -} - -// TODO: Slice implementation. -// This implementation needs to check the slice length. -impl TryFrom<&[i16]> for Color { - type Error = IntoColorError; - - fn try_from(slice: &[i16]) -> Result {} -} - -fn main() { - // Using the `try_from` function. - let c1 = Color::try_from((183, 65, 14)); - println!("{c1:?}"); - - // Since `TryFrom` is implemented for `Color`, we can use `TryInto`. - let c2: Result = [183, 65, 14].try_into(); - println!("{c2:?}"); - - let v = vec![183, 65, 14]; - // With slice we should use the `try_from` function - let c3 = Color::try_from(&v[..]); - println!("{c3:?}"); - // or put the slice within round brackets and use `try_into`. - let c4: Result = (&v[..]).try_into(); - println!("{c4:?}"); -} - -#[cfg(test)] -mod tests { - use super::*; - use IntoColorError::*; - - #[test] - fn test_tuple_out_of_range_positive() { - assert_eq!(Color::try_from((256, 1000, 10000)), Err(IntConversion)); - } - - #[test] - fn test_tuple_out_of_range_negative() { - assert_eq!(Color::try_from((-1, -10, -256)), Err(IntConversion)); - } - - #[test] - fn test_tuple_sum() { - assert_eq!(Color::try_from((-1, 255, 255)), Err(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(IntConversion)); - } - - #[test] - fn test_array_out_of_range_negative() { - let c: Result = [-10, -256, -1].try_into(); - assert_eq!(c, Err(IntConversion)); - } - - #[test] - fn test_array_sum() { - let c: Result = [-1, 255, 255].try_into(); - assert_eq!(c, Err(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(IntConversion)); - } - - #[test] - fn test_slice_out_of_range_negative() { - let arr = [-256, -1, -10]; - assert_eq!(Color::try_from(&arr[..]), Err(IntConversion)); - } - - #[test] - fn test_slice_sum() { - let arr = [-1, 255, 255]; - assert_eq!(Color::try_from(&arr[..]), Err(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(BadLen)); - } - - #[test] - fn test_slice_insufficient_length() { - let v = vec![0, 0]; - assert_eq!(Color::try_from(&v[..]), Err(BadLen)); - } -} diff --git a/rustlings/exercises/23_conversions/using_as.rs b/rustlings/exercises/23_conversions/using_as.rs deleted file mode 100644 index c131d1f..0000000 --- a/rustlings/exercises/23_conversions/using_as.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Type casting in Rust is done via the usage of the `as` operator. -// Note that the `as` operator is not only used when type casting. It also helps -// with renaming imports. - -fn average(values: &[f64]) -> f64 { - let total = values.iter().sum::(); - // TODO: Make a conversion before dividing. - 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/rustlings/exercises/README.md b/rustlings/exercises/README.md deleted file mode 100644 index 1df5cc3..0000000 --- a/rustlings/exercises/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# Exercise to Book Chapter mapping - -| Exercise | Book Chapter | -| ---------------------- | ------------------- | -| variables | §3.1 | -| functions | §3.3 | -| if | §3.5 | -| primitive_types | §3.2, §4.3 | -| vecs | §8.1 | -| move_semantics | §4.1-2 | -| structs | §5.1, §5.3 | -| enums | §6, §18.3 | -| strings | §8.2 | -| modules | §7 | -| hashmaps | §8.3 | -| options | §10.1 | -| error_handling | §9 | -| generics | §10 | -| traits | §10.2 | -| lifetimes | §10.3 | -| tests | §11.1 | -| iterators | §13.2-4 | -| smart_pointers | §15, §16.3 | -| threads | §16.1-3 | -| macros | §20.5 | -| clippy | Appendix D | -| conversions | n/a | diff --git a/rustlings/exercises/quizzes/README.md b/rustlings/exercises/quizzes/README.md deleted file mode 100644 index 4d3bcd9..0000000 --- a/rustlings/exercises/quizzes/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Quizzes - -After every couple of sections, there will be a quiz in this directory that'll test your knowledge on a bunch of sections at once. diff --git a/rustlings/exercises/quizzes/quiz1.rs b/rustlings/exercises/quizzes/quiz1.rs deleted file mode 100644 index b787d7e..0000000 --- a/rustlings/exercises/quizzes/quiz1.rs +++ /dev/null @@ -1,35 +0,0 @@ -// This is a quiz for the following sections: -// - Variables -// - Functions -// - If -// -// Mary is buying apples. The price of an apple is calculated as follows: -// - An apple costs 2 rustbucks. -// - However, if Mary buys more than 40 apples, the price of each apple in the -// entire order is reduced to only 1 rustbuck! - -fn calculate_price_of_apples(n: i32) -> i32 { - if n > 40 { - n - } else { - 2 * n - } -} - -fn main() { - // You can optionally experiment here. -} - -// Don't change the tests! -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn verify_test() { - assert_eq!(calculate_price_of_apples(35), 70); - assert_eq!(calculate_price_of_apples(40), 80); - assert_eq!(calculate_price_of_apples(41), 41); - assert_eq!(calculate_price_of_apples(65), 65); - } -} diff --git a/rustlings/exercises/quizzes/quiz2.rs b/rustlings/exercises/quizzes/quiz2.rs deleted file mode 100644 index fd32810..0000000 --- a/rustlings/exercises/quizzes/quiz2.rs +++ /dev/null @@ -1,81 +0,0 @@ -// This is a quiz for the following sections: -// - Strings -// - Vecs -// - Move semantics -// - Modules -// - Enums -// -// Let's build a little machine in the form of a function. As input, we're going -// to give a list of strings and commands. These commands determine what action -// is going to be applied to the string. It can either be: -// - Uppercase the string -// - Trim the string -// - Append "bar" to the string a specified amount of times -// -// The exact form of this will be: -// - The input is going to be a Vector of 2-length tuples, -// the first element is the string, the second one is the command. -// - The output element is going to be a vector of strings. - -enum Command { - Uppercase, - Trim, - Append(usize), -} - -mod my_module { - use super::Command; - - // TODO: Complete the function as described above. - // pub fn transformer(input: ???) -> ??? { ??? } - pub fn transformer(input: Vec<(String, Command)>) -> Vec { - let mut out = Vec::new(); - for inp in input { - out.push(match inp.1 { - Command::Uppercase => inp.0.to_uppercase(), - Command::Trim => String::from(inp.0.trim()), - Command::Append(n) => { - let mut r = inp.0; - for _ in 0..n { - r += "bar"; - } - r - } - }); - } - out - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - // TODO: What do we need to import to have `transformer` in scope? - // use ???; - use super::Command; - use super::my_module::transformer; - - #[test] - fn it_works() { - let input = vec![ - ("hello".to_string(), Command::Uppercase), - (" all roads lead to rome! ".to_string(), Command::Trim), - ("foo".to_string(), Command::Append(1)), - ("bar".to_string(), Command::Append(5)), - ]; - let output = transformer(input); - - assert_eq!( - output, - [ - "HELLO", - "all roads lead to rome!", - "foobar", - "barbarbarbarbarbar", - ] - ); - } -} diff --git a/rustlings/exercises/quizzes/quiz3.rs b/rustlings/exercises/quizzes/quiz3.rs deleted file mode 100644 index 5bb859f..0000000 --- a/rustlings/exercises/quizzes/quiz3.rs +++ /dev/null @@ -1,64 +0,0 @@ -// This quiz tests: -// - Generics -// - Traits -// -// An imaginary magical school has a new report card generation system written -// in Rust! Currently, the system only supports creating report cards where the -// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the -// school also issues alphabetical grades (A+ -> F-) and needs to be able to -// print both types of report card! -// -// Make the necessary code changes in the struct `ReportCard` and the impl -// block to support alphabetical report cards in addition to numerical ones. - -// TODO: Adjust the struct as described above. -struct ReportCard { - grade: T, - student_name: String, - student_age: u8, -} - -// TODO: Adjust the impl block as described above. -impl ReportCard { - fn print(&self) -> String { - format!( - "{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade, - ) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generate_numeric_report_card() { - let report_card = ReportCard { - grade: 2.1, - student_name: "Tom Wriggle".to_string(), - student_age: 12, - }; - assert_eq!( - report_card.print(), - "Tom Wriggle (12) - achieved a grade of 2.1", - ); - } - - #[test] - fn generate_alphabetic_report_card() { - let report_card = ReportCard { - grade: "A+", - student_name: "Gary Plotter".to_string(), - student_age: 11, - }; - assert_eq!( - report_card.print(), - "Gary Plotter (11) - achieved a grade of A+", - ); - } -} diff --git a/rustlings/rust-analyzer.toml b/rustlings/rust-analyzer.toml deleted file mode 100644 index 977b6ce..0000000 --- a/rustlings/rust-analyzer.toml +++ /dev/null @@ -1,3 +0,0 @@ -check.command = "clippy" -check.extraArgs = ["--profile", "test"] -cargo.targetDir = true diff --git a/rustlings/solutions/00_intro/intro1.rs b/rustlings/solutions/00_intro/intro1.rs deleted file mode 100644 index 4fe8454..0000000 --- a/rustlings/solutions/00_intro/intro1.rs +++ /dev/null @@ -1,5 +0,0 @@ -fn main() { - // Congratulations, you finished the first exercise 🎉 - // As an introduction to Rustlings, the first exercise only required - // entering `n` in the terminal to go to the next exercise. -} diff --git a/rustlings/solutions/00_intro/intro2.rs b/rustlings/solutions/00_intro/intro2.rs deleted file mode 100644 index b8e031a..0000000 --- a/rustlings/solutions/00_intro/intro2.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // `println!` instead of `printline!`. - println!("Hello world!"); -} diff --git a/rustlings/solutions/01_variables/variables1.rs b/rustlings/solutions/01_variables/variables1.rs deleted file mode 100644 index 58d046b..0000000 --- a/rustlings/solutions/01_variables/variables1.rs +++ /dev/null @@ -1,6 +0,0 @@ -fn main() { - // Declaring variables requires the `let` keyword. - let x = 5; - - println!("x has the value {x}"); -} diff --git a/rustlings/solutions/01_variables/variables2.rs b/rustlings/solutions/01_variables/variables2.rs deleted file mode 100644 index 50b8d1b..0000000 --- a/rustlings/solutions/01_variables/variables2.rs +++ /dev/null @@ -1,16 +0,0 @@ -fn main() { - // The easiest way to fix the compiler error is to initialize the - // variable `x`. By setting its value to an integer, Rust infers its type - // as `i32` which is the default type for integers. - let x = 42; - - // But we can enforce a type different from the default `i32` by adding - // a type annotation: - // let x: u8 = 42; - - if x == 10 { - println!("x is ten!"); - } else { - println!("x is not ten!"); - } -} diff --git a/rustlings/solutions/01_variables/variables3.rs b/rustlings/solutions/01_variables/variables3.rs deleted file mode 100644 index 15f6557..0000000 --- a/rustlings/solutions/01_variables/variables3.rs +++ /dev/null @@ -1,15 +0,0 @@ -#![allow(clippy::needless_late_init)] - -fn main() { - // Reading uninitialized variables isn't allowed in Rust! - // Therefore, we need to assign a value first. - let x: i32 = 42; - - println!("Number {x}"); - - // It is possible to declare a variable and initialize it later. - // But it can't be used before initialization. - let y: i32; - y = 42; - println!("Number {y}"); -} diff --git a/rustlings/solutions/01_variables/variables4.rs b/rustlings/solutions/01_variables/variables4.rs deleted file mode 100644 index 7de6bcb..0000000 --- a/rustlings/solutions/01_variables/variables4.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn main() { - // In Rust, variables are immutable by default. - // Adding the `mut` keyword after `let` makes the declared variable mutable. - let mut x = 3; - println!("Number {x}"); - - x = 5; - println!("Number {x}"); -} diff --git a/rustlings/solutions/01_variables/variables5.rs b/rustlings/solutions/01_variables/variables5.rs deleted file mode 100644 index 0ea3903..0000000 --- a/rustlings/solutions/01_variables/variables5.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn main() { - let number = "T-H-R-E-E"; - println!("Spell a number: {number}"); - - // Using variable shadowing - // https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing - let number = 3; - println!("Number plus two is: {}", number + 2); -} diff --git a/rustlings/solutions/01_variables/variables6.rs b/rustlings/solutions/01_variables/variables6.rs deleted file mode 100644 index 25b7a1e..0000000 --- a/rustlings/solutions/01_variables/variables6.rs +++ /dev/null @@ -1,6 +0,0 @@ -// The type of constants must always be annotated. -const NUMBER: u64 = 3; - -fn main() { - println!("Number: {NUMBER}"); -} diff --git a/rustlings/solutions/02_functions/functions1.rs b/rustlings/solutions/02_functions/functions1.rs deleted file mode 100644 index dc52744..0000000 --- a/rustlings/solutions/02_functions/functions1.rs +++ /dev/null @@ -1,8 +0,0 @@ -// Some function with the name `call_me` without arguments or a return value. -fn call_me() { - println!("Hello world!"); -} - -fn main() { - call_me(); -} diff --git a/rustlings/solutions/02_functions/functions2.rs b/rustlings/solutions/02_functions/functions2.rs deleted file mode 100644 index f14ffa3..0000000 --- a/rustlings/solutions/02_functions/functions2.rs +++ /dev/null @@ -1,11 +0,0 @@ -// The type of function arguments must be annotated. -// Added the type annotation `u64`. -fn call_me(num: u64) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} - -fn main() { - call_me(3); -} diff --git a/rustlings/solutions/02_functions/functions3.rs b/rustlings/solutions/02_functions/functions3.rs deleted file mode 100644 index ce5fe8e..0000000 --- a/rustlings/solutions/02_functions/functions3.rs +++ /dev/null @@ -1,10 +0,0 @@ -fn call_me(num: u8) { - for i in 0..num { - println!("Ring! Call number {}", i + 1); - } -} - -fn main() { - // `call_me` expects an argument. - call_me(5); -} diff --git a/rustlings/solutions/02_functions/functions4.rs b/rustlings/solutions/02_functions/functions4.rs deleted file mode 100644 index f823de2..0000000 --- a/rustlings/solutions/02_functions/functions4.rs +++ /dev/null @@ -1,17 +0,0 @@ -fn is_even(num: i64) -> bool { - num % 2 == 0 -} - -// The return type must always be annotated. -fn sale_price(price: i64) -> i64 { - if is_even(price) { - price - 10 - } else { - price - 3 - } -} - -fn main() { - let original_price = 51; - println!("Your sale price is {}", sale_price(original_price)); -} diff --git a/rustlings/solutions/02_functions/functions5.rs b/rustlings/solutions/02_functions/functions5.rs deleted file mode 100644 index 677f327..0000000 --- a/rustlings/solutions/02_functions/functions5.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn square(num: i32) -> i32 { - // Removed the semicolon `;` at the end of the line below to implicitly return the result. - num * num -} - -fn main() { - let answer = square(3); - println!("The square of 3 is {answer}"); -} diff --git a/rustlings/solutions/03_if/if1.rs b/rustlings/solutions/03_if/if1.rs deleted file mode 100644 index 8512a60..0000000 --- a/rustlings/solutions/03_if/if1.rs +++ /dev/null @@ -1,28 +0,0 @@ -fn bigger(a: i32, b: i32) -> i32 { - if a > b { a } else { b } -} - -fn main() { - // You can optionally experiment here. -} - -// 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/rustlings/solutions/03_if/if2.rs b/rustlings/solutions/03_if/if2.rs deleted file mode 100644 index 21c0dcd..0000000 --- a/rustlings/solutions/03_if/if2.rs +++ /dev/null @@ -1,35 +0,0 @@ -fn picky_eater(food: &str) -> &str { - if food == "strawberry" { - "Yummy!" - } else if food == "potato" { - "I guess I can eat that." - } else { - "No thanks!" - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn yummy_food() { - assert_eq!(picky_eater("strawberry"), "Yummy!"); - } - - #[test] - fn neutral_food() { - assert_eq!(picky_eater("potato"), "I guess I can eat that."); - } - - #[test] - fn default_disliked_food() { - assert_eq!(picky_eater("broccoli"), "No thanks!"); - assert_eq!(picky_eater("gummy bears"), "No thanks!"); - assert_eq!(picky_eater("literally anything"), "No thanks!"); - } -} diff --git a/rustlings/solutions/03_if/if3.rs b/rustlings/solutions/03_if/if3.rs deleted file mode 100644 index 571644d..0000000 --- a/rustlings/solutions/03_if/if3.rs +++ /dev/null @@ -1,53 +0,0 @@ -fn animal_habitat(animal: &str) -> &str { - let identifier = if animal == "crab" { - 1 - } else if animal == "gopher" { - 2 - } else if animal == "snake" { - 3 - } else { - // Any unused identifier. - 4 - }; - - // Instead of such an identifier, you would use an enum in Rust. - // But we didn't get into enums yet. - if identifier == 1 { - "Beach" - } else if identifier == 2 { - "Burrow" - } else if identifier == 3 { - "Desert" - } else { - "Unknown" - } -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/solutions/04_primitive_types/primitive_types1.rs b/rustlings/solutions/04_primitive_types/primitive_types1.rs deleted file mode 100644 index fac6ec0..0000000 --- a/rustlings/solutions/04_primitive_types/primitive_types1.rs +++ /dev/null @@ -1,11 +0,0 @@ -fn main() { - let is_morning = true; - if is_morning { - println!("Good morning!"); - } - - let is_evening = !is_morning; - if is_evening { - println!("Good evening!"); - } -} diff --git a/rustlings/solutions/04_primitive_types/primitive_types2.rs b/rustlings/solutions/04_primitive_types/primitive_types2.rs deleted file mode 100644 index eecc680..0000000 --- a/rustlings/solutions/04_primitive_types/primitive_types2.rs +++ /dev/null @@ -1,21 +0,0 @@ -fn main() { - 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!"); - } - - // Example with an emoji. - let your_character = '🦀'; - - if your_character.is_alphabetic() { - println!("Alphabetical!"); - } else if your_character.is_numeric() { - println!("Numerical!"); - } else { - println!("Neither alphabetic nor numeric!"); - } -} diff --git a/rustlings/solutions/04_primitive_types/primitive_types3.rs b/rustlings/solutions/04_primitive_types/primitive_types3.rs deleted file mode 100644 index 8dd109f..0000000 --- a/rustlings/solutions/04_primitive_types/primitive_types3.rs +++ /dev/null @@ -1,11 +0,0 @@ -fn main() { - // An array with 100 elements of the value 42. - let a = [42; 100]; - - 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/rustlings/solutions/04_primitive_types/primitive_types4.rs b/rustlings/solutions/04_primitive_types/primitive_types4.rs deleted file mode 100644 index 4807e66..0000000 --- a/rustlings/solutions/04_primitive_types/primitive_types4.rs +++ /dev/null @@ -1,23 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn slice_out_of_array() { - let a = [1, 2, 3, 4, 5]; - // 0 1 2 3 4 <- indices - // ------- - // | - // +--- slice - - // Note that the upper index 4 is excluded. - let nice_slice = &a[1..4]; - assert_eq!([2, 3, 4], nice_slice); - - // The upper index can be included by using the syntax `..=` (with `=` sign) - let nice_slice = &a[1..=3]; - assert_eq!([2, 3, 4], nice_slice); - } -} diff --git a/rustlings/solutions/04_primitive_types/primitive_types5.rs b/rustlings/solutions/04_primitive_types/primitive_types5.rs deleted file mode 100644 index 46d7ae8..0000000 --- a/rustlings/solutions/04_primitive_types/primitive_types5.rs +++ /dev/null @@ -1,8 +0,0 @@ -fn main() { - let cat = ("Furry McFurson", 3.5); - - // Destructuring the tuple. - let (name, age) = cat; - - println!("{name} is {age} years old"); -} diff --git a/rustlings/solutions/04_primitive_types/primitive_types6.rs b/rustlings/solutions/04_primitive_types/primitive_types6.rs deleted file mode 100644 index 9b7c277..0000000 --- a/rustlings/solutions/04_primitive_types/primitive_types6.rs +++ /dev/null @@ -1,16 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn indexing_tuple() { - let numbers = (1, 2, 3); - - // Tuple indexing syntax. - let second = numbers.1; - - assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); - } -} diff --git a/rustlings/solutions/05_vecs/vecs1.rs b/rustlings/solutions/05_vecs/vecs1.rs deleted file mode 100644 index 55b5676..0000000 --- a/rustlings/solutions/05_vecs/vecs1.rs +++ /dev/null @@ -1,23 +0,0 @@ -fn array_and_vec() -> ([i32; 4], Vec) { - let a = [10, 20, 30, 40]; // Array - - // Used the `vec!` macro. - let v = vec![10, 20, 30, 40]; - - (a, v) -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/solutions/05_vecs/vecs2.rs b/rustlings/solutions/05_vecs/vecs2.rs deleted file mode 100644 index 87f7625..0000000 --- a/rustlings/solutions/05_vecs/vecs2.rs +++ /dev/null @@ -1,55 +0,0 @@ -fn vec_loop(input: &[i32]) -> Vec { - let mut output = Vec::new(); - - for element in input { - output.push(2 * element); - } - - output -} - -fn vec_map_example(input: &[i32]) -> Vec { - // An example of collecting a vector after mapping. - // We map each element of the `input` slice to its value plus 1. - // If the input is `[1, 2, 3]`, the output is `[2, 3, 4]`. - input.iter().map(|element| element + 1).collect() -} - -fn vec_map(input: &[i32]) -> Vec { - // We will dive deeper into iterators, but for now, this is all what you - // had to do! - // Advanced note: This method is more efficient because it automatically - // preallocates enough capacity. This can be done manually in `vec_loop` - // using `Vec::with_capacity(input.len())` instead of `Vec::new()`. - input.iter().map(|element| 2 * element).collect() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_vec_loop() { - let input = [2, 4, 6, 8, 10]; - let ans = vec_loop(&input); - assert_eq!(ans, [4, 8, 12, 16, 20]); - } - - #[test] - fn test_vec_map_example() { - let input = [1, 2, 3]; - let ans = vec_map_example(&input); - assert_eq!(ans, [2, 3, 4]); - } - - #[test] - fn test_vec_map() { - let input = [2, 4, 6, 8, 10]; - let ans = vec_map(&input); - assert_eq!(ans, [4, 8, 12, 16, 20]); - } -} diff --git a/rustlings/solutions/06_move_semantics/move_semantics1.rs b/rustlings/solutions/06_move_semantics/move_semantics1.rs deleted file mode 100644 index ac34e7a..0000000 --- a/rustlings/solutions/06_move_semantics/move_semantics1.rs +++ /dev/null @@ -1,25 +0,0 @@ -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - // ^^^ added - - vec.push(88); - - vec -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn move_semantics1() { - let vec0 = vec![22, 44, 66]; - let vec1 = fill_vec(vec0); - // `vec0` can't be accessed anymore because it is moved to `fill_vec`. - assert_eq!(vec1, vec![22, 44, 66, 88]); - } -} diff --git a/rustlings/solutions/06_move_semantics/move_semantics2.rs b/rustlings/solutions/06_move_semantics/move_semantics2.rs deleted file mode 100644 index 7bcd33a..0000000 --- a/rustlings/solutions/06_move_semantics/move_semantics2.rs +++ /dev/null @@ -1,28 +0,0 @@ -fn fill_vec(vec: Vec) -> Vec { - let mut vec = vec; - - vec.push(88); - - vec -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn move_semantics2() { - let vec0 = vec![22, 44, 66]; - - // Cloning `vec0` so that the clone is moved into `fill_vec`, not `vec0` - // itself. - let vec1 = fill_vec(vec0.clone()); - - assert_eq!(vec0, [22, 44, 66]); - assert_eq!(vec1, [22, 44, 66, 88]); - } -} diff --git a/rustlings/solutions/06_move_semantics/move_semantics3.rs b/rustlings/solutions/06_move_semantics/move_semantics3.rs deleted file mode 100644 index 7ba4006..0000000 --- a/rustlings/solutions/06_move_semantics/move_semantics3.rs +++ /dev/null @@ -1,22 +0,0 @@ -fn fill_vec(mut vec: Vec) -> Vec { - // ^^^ added - vec.push(88); - - vec -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn move_semantics3() { - let vec0 = vec![22, 44, 66]; - let vec1 = fill_vec(vec0); - assert_eq!(vec1, [22, 44, 66, 88]); - } -} diff --git a/rustlings/solutions/06_move_semantics/move_semantics4.rs b/rustlings/solutions/06_move_semantics/move_semantics4.rs deleted file mode 100644 index 1a39d4f..0000000 --- a/rustlings/solutions/06_move_semantics/move_semantics4.rs +++ /dev/null @@ -1,19 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn move_semantics4() { - let mut x = Vec::new(); - let y = &mut x; - // `y` used here. - y.push(42); - // The mutable reference `y` is not used anymore, - // therefore a new reference can be created. - let z = &mut x; - z.push(13); - assert_eq!(x, [42, 13]); - } -} diff --git a/rustlings/solutions/06_move_semantics/move_semantics5.rs b/rustlings/solutions/06_move_semantics/move_semantics5.rs deleted file mode 100644 index 1410e91..0000000 --- a/rustlings/solutions/06_move_semantics/move_semantics5.rs +++ /dev/null @@ -1,23 +0,0 @@ -#![allow(clippy::ptr_arg)] - -// Borrows instead of taking ownership. -// It is recommended to use `&str` instead of `&String` here. But this is -// enough for now because we didn't handle strings yet. -fn get_char(data: &String) -> char { - data.chars().last().unwrap() -} - -// Takes ownership instead of borrowing. -fn string_uppercase(mut data: String) { - data = data.to_uppercase(); - - println!("{data}"); -} - -fn main() { - let data = "Rust is great!".to_string(); - - get_char(&data); - - string_uppercase(data); -} diff --git a/rustlings/solutions/07_structs/structs1.rs b/rustlings/solutions/07_structs/structs1.rs deleted file mode 100644 index 98fafcc..0000000 --- a/rustlings/solutions/07_structs/structs1.rs +++ /dev/null @@ -1,49 +0,0 @@ -struct ColorRegularStruct { - red: u8, - green: u8, - blue: u8, -} - -struct ColorTupleStruct(u8, u8, u8); - -#[derive(Debug)] -struct UnitStruct; - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn regular_structs() { - let green = ColorRegularStruct { - red: 0, - green: 255, - blue: 0, - }; - - assert_eq!(green.red, 0); - assert_eq!(green.green, 255); - assert_eq!(green.blue, 0); - } - - #[test] - fn tuple_structs() { - let green = ColorTupleStruct(0, 255, 0); - - assert_eq!(green.0, 0); - assert_eq!(green.1, 255); - assert_eq!(green.2, 0); - } - - #[test] - fn unit_structs() { - let unit_struct = UnitStruct; - let message = format!("{unit_struct:?}s are fun!"); - - assert_eq!(message, "UnitStructs are fun!"); - } -} diff --git a/rustlings/solutions/07_structs/structs2.rs b/rustlings/solutions/07_structs/structs2.rs deleted file mode 100644 index 589dd93..0000000 --- a/rustlings/solutions/07_structs/structs2.rs +++ /dev/null @@ -1,51 +0,0 @@ -#[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, - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn your_order() { - let order_template = create_order_template(); - - let your_order = Order { - name: String::from("Hacker in Rust"), - count: 1, - // Struct update syntax - ..order_template - }; - - assert_eq!(your_order.name, "Hacker in Rust"); - assert_eq!(your_order.year, order_template.year); - assert_eq!(your_order.made_by_phone, order_template.made_by_phone); - 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/rustlings/solutions/07_structs/structs3.rs b/rustlings/solutions/07_structs/structs3.rs deleted file mode 100644 index 3f878cc..0000000 --- a/rustlings/solutions/07_structs/structs3.rs +++ /dev/null @@ -1,83 +0,0 @@ -#[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) -> Self { - if weight_in_grams < 10 { - // This isn't how you should handle errors in Rust, but we will - // learn about error handling later. - panic!("Can't ship a package with weight below 10 grams"); - } - - Self { - sender_country, - recipient_country, - weight_in_grams, - } - } - - fn is_international(&self) -> bool { - // ^^^^^^^ added - self.sender_country != self.recipient_country - } - - fn get_fees(&self, cents_per_gram: u32) -> u32 { - // ^^^^^^ added - self.weight_in_grams * cents_per_gram - } -} - -fn main() { - // You can optionally experiment 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/rustlings/solutions/08_enums/enums1.rs b/rustlings/solutions/08_enums/enums1.rs deleted file mode 100644 index 97a5cc0..0000000 --- a/rustlings/solutions/08_enums/enums1.rs +++ /dev/null @@ -1,16 +0,0 @@ -#[derive(Debug)] -enum Message { - Resize, - Move, - Echo, - ChangeColor, - Quit, -} - -fn main() { - println!("{:?}", Message::Resize); - println!("{:?}", Message::Move); - println!("{:?}", Message::Echo); - println!("{:?}", Message::ChangeColor); - println!("{:?}", Message::Quit); -} diff --git a/rustlings/solutions/08_enums/enums2.rs b/rustlings/solutions/08_enums/enums2.rs deleted file mode 100644 index 07aee26..0000000 --- a/rustlings/solutions/08_enums/enums2.rs +++ /dev/null @@ -1,37 +0,0 @@ -#[derive(Debug)] -struct Point { - x: u64, - y: u64, -} - -#[derive(Debug)] -enum Message { - Resize { width: u64, height: u64 }, - Move(Point), - Echo(String), - ChangeColor(u8, u8, u8), - Quit, -} - -impl Message { - fn call(&self) { - println!("{self:?}"); - } -} - -fn main() { - let messages = [ - Message::Resize { - width: 10, - height: 30, - }, - Message::Move(Point { x: 10, y: 15 }), - Message::Echo(String::from("hello world")), - Message::ChangeColor(200, 255, 255), - Message::Quit, - ]; - - for message in &messages { - message.call(); - } -} diff --git a/rustlings/solutions/08_enums/enums3.rs b/rustlings/solutions/08_enums/enums3.rs deleted file mode 100644 index 94cf250..0000000 --- a/rustlings/solutions/08_enums/enums3.rs +++ /dev/null @@ -1,92 +0,0 @@ -struct Point { - x: u64, - y: u64, -} - -enum Message { - Resize { width: u64, height: u64 }, - Move(Point), - Echo(String), - ChangeColor(u8, u8, u8), - Quit, -} - -struct State { - width: u64, - height: u64, - position: Point, - message: String, - color: (u8, u8, u8), - quit: bool, -} - -impl State { - fn resize(&mut self, width: u64, height: u64) { - self.width = width; - self.height = height; - } - - fn move_position(&mut self, point: Point) { - self.position = point; - } - - fn echo(&mut self, s: String) { - self.message = s; - } - - fn change_color(&mut self, red: u8, green: u8, blue: u8) { - self.color = (red, green, blue); - } - - fn quit(&mut self) { - self.quit = true; - } - - fn process(&mut self, message: Message) { - match message { - Message::Resize { width, height } => self.resize(width, height), - Message::Move(point) => self.move_position(point), - Message::Echo(string) => self.echo(string), - Message::ChangeColor(red, green, blue) => self.change_color(red, green, blue), - Message::Quit => self.quit(), - } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_match_message_call() { - let mut state = State { - width: 0, - height: 0, - position: Point { x: 0, y: 0 }, - message: String::from("hello world"), - color: (0, 0, 0), - quit: false, - }; - - state.process(Message::Resize { - width: 10, - height: 30, - }); - state.process(Message::Move(Point { x: 10, y: 15 })); - state.process(Message::Echo(String::from("Hello world!"))); - state.process(Message::ChangeColor(255, 0, 255)); - state.process(Message::Quit); - - assert_eq!(state.width, 10); - assert_eq!(state.height, 30); - assert_eq!(state.position.x, 10); - assert_eq!(state.position.y, 15); - assert_eq!(state.message, "Hello world!"); - assert_eq!(state.color, (255, 0, 255)); - assert!(state.quit); - } -} diff --git a/rustlings/solutions/09_strings/strings1.rs b/rustlings/solutions/09_strings/strings1.rs deleted file mode 100644 index f7ba811..0000000 --- a/rustlings/solutions/09_strings/strings1.rs +++ /dev/null @@ -1,9 +0,0 @@ -fn current_favorite_color() -> String { - // Equivalent to `String::from("blue")` - "blue".to_string() -} - -fn main() { - let answer = current_favorite_color(); - println!("My current favorite color is {answer}"); -} diff --git a/rustlings/solutions/09_strings/strings2.rs b/rustlings/solutions/09_strings/strings2.rs deleted file mode 100644 index 7de311f..0000000 --- a/rustlings/solutions/09_strings/strings2.rs +++ /dev/null @@ -1,15 +0,0 @@ -fn is_a_color_word(attempt: &str) -> bool { - attempt == "green" || attempt == "blue" || attempt == "red" -} - -fn main() { - let word = String::from("green"); - - if is_a_color_word(&word) { - // ^ added to have `&String` which is automatically - // coerced to `&str` by the compiler. - println!("That is a color word I know!"); - } else { - println!("That is not a color word I know."); - } -} diff --git a/rustlings/solutions/09_strings/strings3.rs b/rustlings/solutions/09_strings/strings3.rs deleted file mode 100644 index ee6b56a..0000000 --- a/rustlings/solutions/09_strings/strings3.rs +++ /dev/null @@ -1,49 +0,0 @@ -fn trim_me(input: &str) -> &str { - input.trim() -} - -fn compose_me(input: &str) -> String { - // The macro `format!` has the same syntax as `println!`, but it returns a - // string instead of printing it to the terminal. - // Equivalent to `input.to_string() + " world!"` - format!("{input} world!") -} - -fn replace_me(input: &str) -> String { - input.replace("cars", "balloons") -} - -fn main() { - // You can optionally experiment here. -} - -#[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!"); - assert_eq!(trim_me("Hi!"), "Hi!"); - } - - #[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/rustlings/solutions/09_strings/strings4.rs b/rustlings/solutions/09_strings/strings4.rs deleted file mode 100644 index 3c69b97..0000000 --- a/rustlings/solutions/09_strings/strings4.rs +++ /dev/null @@ -1,38 +0,0 @@ -fn string_slice(arg: &str) { - println!("{arg}"); -} - -fn string(arg: String) { - println!("{arg}"); -} - -fn main() { - string_slice("blue"); - - string("red".to_string()); - - string(String::from("hi")); - - string("rust is fun!".to_owned()); - - // Here, both answers work. - // `.into()` converts a type into an expected type. - // If it is called where `String` is expected, it will convert `&str` to `String`. - string("nice weather".into()); - // But if it is called where `&str` is expected, then `&str` is kept `&str` since no conversion is needed. - // If you remove the `#[allow(…)]` line, then Clippy will tell you to remove `.into()` below since it is a useless conversion. - #[allow(clippy::useless_conversion)] - string_slice("nice weather".into()); - - string(format!("Interpolation {}", "Station")); - - // WARNING: This is byte indexing, not character indexing. - // Character indexing can be done using `s.chars().nth(INDEX)`. - string_slice(&String::from("abc")[0..1]); - - string_slice(" hello there ".trim()); - - string("Happy Monday!".replace("Mon", "Tues")); - - string("mY sHiFt KeY iS sTiCkY".to_lowercase()); -} diff --git a/rustlings/solutions/10_modules/modules1.rs b/rustlings/solutions/10_modules/modules1.rs deleted file mode 100644 index 873b412..0000000 --- a/rustlings/solutions/10_modules/modules1.rs +++ /dev/null @@ -1,15 +0,0 @@ -mod sausage_factory { - fn get_secret_recipe() -> String { - String::from("Ginger") - } - - // Added `pub` before `fn` to make the function accessible outside the module. - pub fn make_sausage() { - get_secret_recipe(); - println!("sausage!"); - } -} - -fn main() { - sausage_factory::make_sausage(); -} diff --git a/rustlings/solutions/10_modules/modules2.rs b/rustlings/solutions/10_modules/modules2.rs deleted file mode 100644 index 55c316d..0000000 --- a/rustlings/solutions/10_modules/modules2.rs +++ /dev/null @@ -1,23 +0,0 @@ -mod delicious_snacks { - // Added `pub` and used the expected alias after `as`. - pub use self::fruits::PEAR as fruit; - pub use self::veggies::CUCUMBER as veggie; - - mod fruits { - pub const PEAR: &str = "Pear"; - pub const APPLE: &str = "Apple"; - } - - mod veggies { - pub const CUCUMBER: &str = "Cucumber"; - pub const CARROT: &str = "Carrot"; - } -} - -fn main() { - println!( - "favorite snacks: {} and {}", - delicious_snacks::fruit, - delicious_snacks::veggie, - ); -} diff --git a/rustlings/solutions/10_modules/modules3.rs b/rustlings/solutions/10_modules/modules3.rs deleted file mode 100644 index 99ff5a7..0000000 --- a/rustlings/solutions/10_modules/modules3.rs +++ /dev/null @@ -1,8 +0,0 @@ -use std::time::{SystemTime, UNIX_EPOCH}; - -fn main() { - match SystemTime::now().duration_since(UNIX_EPOCH) { - Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), - Err(_) => panic!("SystemTime before UNIX EPOCH!"), - } -} diff --git a/rustlings/solutions/11_hashmaps/hashmaps1.rs b/rustlings/solutions/11_hashmaps/hashmaps1.rs deleted file mode 100644 index 3a787c4..0000000 --- a/rustlings/solutions/11_hashmaps/hashmaps1.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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 3 different -// types of fruits (e.g apple, banana, mango) in the basket and the total count -// of all the fruits should be at least 5. - -use std::collections::HashMap; - -fn fruit_basket() -> HashMap { - // Declare the hash map. - let mut basket = HashMap::new(); - - // Two bananas are already given for you :) - basket.insert(String::from("banana"), 2); - - // Put more fruits in your basket. - basket.insert(String::from("apple"), 3); - basket.insert(String::from("mango"), 1); - - basket -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/solutions/11_hashmaps/hashmaps2.rs b/rustlings/solutions/11_hashmaps/hashmaps2.rs deleted file mode 100644 index 75e6ec2..0000000 --- a/rustlings/solutions/11_hashmaps/hashmaps2.rs +++ /dev/null @@ -1,96 +0,0 @@ -// 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 the fruits that are already in the basket (Apple, -// Mango, and Lychee). - -use std::collections::HashMap; - -#[derive(Hash, PartialEq, Eq, Debug)] -enum Fruit { - Apple, - Banana, - Mango, - Lychee, - Pineapple, -} - -fn fruit_basket(basket: &mut HashMap) { - let fruit_kinds = [ - Fruit::Apple, - Fruit::Banana, - Fruit::Mango, - Fruit::Lychee, - Fruit::Pineapple, - ]; - - for fruit in fruit_kinds { - // If fruit doesn't exist, insert it with some value. - basket.entry(fruit).or_insert(5); - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - // Don't modify this function! - fn get_fruit_basket() -> HashMap { - let content = [(Fruit::Apple, 4), (Fruit::Mango, 2), (Fruit::Lychee, 5)]; - HashMap::from_iter(content) - } - - #[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 fruit_kinds = [ - Fruit::Apple, - Fruit::Banana, - Fruit::Mango, - Fruit::Lychee, - Fruit::Pineapple, - ]; - - let mut basket = get_fruit_basket(); - fruit_basket(&mut basket); - - for fruit_kind in fruit_kinds { - let Some(amount) = basket.get(&fruit_kind) else { - panic!("Fruit kind {fruit_kind:?} was not found in basket"); - }; - assert!(*amount > 0); - } - } -} diff --git a/rustlings/solutions/11_hashmaps/hashmaps3.rs b/rustlings/solutions/11_hashmaps/hashmaps3.rs deleted file mode 100644 index 485bf83..0000000 --- a/rustlings/solutions/11_hashmaps/hashmaps3.rs +++ /dev/null @@ -1,85 +0,0 @@ -// 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, the total -// number of goals the team scored, and the total number of goals the team -// conceded. - -use std::collections::HashMap; - -// A structure to store the goal details of a team. -#[derive(Default)] -struct TeamScores { - goals_scored: u8, - goals_conceded: u8, -} - -fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { - // The name of the team is the key and its associated struct is the value. - let mut scores = HashMap::<&str, TeamScores>::new(); - - for line in results.lines() { - let mut split_iterator = line.split(','); - // NOTE: We use `unwrap` because we didn't deal with error handling yet. - let team_1_name = split_iterator.next().unwrap(); - let team_2_name = split_iterator.next().unwrap(); - let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); - let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); - - // Insert the default with zeros if a team doesn't exist yet. - let team_1 = scores.entry(team_1_name).or_default(); - // Update the values. - team_1.goals_scored += team_1_score; - team_1.goals_conceded += team_2_score; - - // Similarly for the second team. - let team_2 = scores.entry(team_2_name).or_default(); - team_2.goals_scored += team_2_score; - team_2.goals_conceded += team_1_score; - } - - scores -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - const RESULTS: &str = "England,France,4,2 -France,Italy,3,1 -Poland,Spain,2,0 -Germany,England,2,1 -England,Spain,1,0"; - - #[test] - fn build_scores() { - let scores = build_scores_table(RESULTS); - - assert!( - ["England", "France", "Germany", "Italy", "Poland", "Spain"] - .into_iter() - .all(|team_name| scores.contains_key(team_name)) - ); - } - - #[test] - fn validate_team_score_1() { - let scores = build_scores_table(RESULTS); - let team = scores.get("England").unwrap(); - assert_eq!(team.goals_scored, 6); - assert_eq!(team.goals_conceded, 4); - } - - #[test] - fn validate_team_score_2() { - let scores = build_scores_table(RESULTS); - let team = scores.get("Spain").unwrap(); - assert_eq!(team.goals_scored, 0); - assert_eq!(team.goals_conceded, 3); - } -} diff --git a/rustlings/solutions/12_options/options1.rs b/rustlings/solutions/12_options/options1.rs deleted file mode 100644 index 4d615dd..0000000 --- a/rustlings/solutions/12_options/options1.rs +++ /dev/null @@ -1,39 +0,0 @@ -// This function returns how much icecream there is left in the fridge. -// If it's before 22:00 (24-hour system), then 5 scoops are left. At 22:00, -// someone eats it all, so no icecream is left (value 0). Return `None` if -// `hour_of_day` is higher than 23. -fn maybe_icecream(hour_of_day: u16) -> Option { - match hour_of_day { - 0..=21 => Some(5), - 22..=23 => Some(0), - _ => None, - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn raw_value() { - // Using `unwrap` is fine in a test. - let icecreams = maybe_icecream(12).unwrap(); - - assert_eq!(icecreams, 5); - } - - #[test] - fn check_icecream() { - assert_eq!(maybe_icecream(0), Some(5)); - assert_eq!(maybe_icecream(9), Some(5)); - assert_eq!(maybe_icecream(18), Some(5)); - assert_eq!(maybe_icecream(22), Some(0)); - assert_eq!(maybe_icecream(23), Some(0)); - assert_eq!(maybe_icecream(24), None); - assert_eq!(maybe_icecream(25), None); - } -} diff --git a/rustlings/solutions/12_options/options2.rs b/rustlings/solutions/12_options/options2.rs deleted file mode 100644 index 0f24665..0000000 --- a/rustlings/solutions/12_options/options2.rs +++ /dev/null @@ -1,37 +0,0 @@ -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn simple_option() { - let target = "rustlings"; - let optional_target = Some(target); - - // if-let - if let Some(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 { - optional_integers.push(Some(i)); - } - - let mut cursor = range; - - // while-let with nested pattern matching - while let Some(Some(integer)) = optional_integers.pop() { - assert_eq!(integer, cursor); - cursor -= 1; - } - - assert_eq!(cursor, 0); - } -} diff --git a/rustlings/solutions/12_options/options3.rs b/rustlings/solutions/12_options/options3.rs deleted file mode 100644 index c918f71..0000000 --- a/rustlings/solutions/12_options/options3.rs +++ /dev/null @@ -1,27 +0,0 @@ -#[derive(Debug)] -struct Point { - x: i32, - y: i32, -} - -fn main() { - let optional_point = Some(Point { x: 100, y: 200 }); - - // Solution 1: Matching over the `Option` (not `&Option`) but without moving - // out of the `Some` variant. - match optional_point { - Some(ref p) => println!("Coordinates are {},{}", p.x, p.y), - // ^^^ added - _ => panic!("No match!"), - } - - // Solution 2: Matching over a reference (`&Option`) by added `&` before - // `optional_point`. - match &optional_point { - //^ added - Some(p) => println!("Coordinates are {},{}", p.x, p.y), - _ => panic!("No match!"), - } - - println!("{optional_point:?}"); -} diff --git a/rustlings/solutions/13_error_handling/errors1.rs b/rustlings/solutions/13_error_handling/errors1.rs deleted file mode 100644 index f552ca7..0000000 --- a/rustlings/solutions/13_error_handling/errors1.rs +++ /dev/null @@ -1,37 +0,0 @@ -fn generate_nametag_text(name: String) -> Result { - // ^^^^^^ ^^^^^^ - if name.is_empty() { - // `Err(String)` instead of `None`. - Err("Empty names aren't allowed".to_string()) - } else { - // `Ok` instead of `Some`. - Ok(format!("Hi! My name is {name}")) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generates_nametag_text_for_a_nonempty_name() { - assert_eq!( - generate_nametag_text("Beyoncé".to_string()).as_deref(), - Ok("Hi! My name is Beyoncé"), - ); - } - - #[test] - fn explains_why_generating_nametag_text_fails() { - assert_eq!( - generate_nametag_text(String::new()) - .as_ref() - .map_err(|e| e.as_str()), - Err("Empty names aren't allowed"), - ); - } -} diff --git a/rustlings/solutions/13_error_handling/errors2.rs b/rustlings/solutions/13_error_handling/errors2.rs deleted file mode 100644 index f0e144e..0000000 --- a/rustlings/solutions/13_error_handling/errors2.rs +++ /dev/null @@ -1,58 +0,0 @@ -// 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, we get it as a string. They might have -// typed anything, not just numbers! -// -// Right now, this function isn't handling the error case at all. 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`. 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! - -use std::num::ParseIntError; - -#[allow(unused_variables, clippy::question_mark)] -fn total_cost(item_quantity: &str) -> Result { - let processing_fee = 1; - let cost_per_item = 5; - - // Added `?` to propagate the error. - let qty = item_quantity.parse::()?; - // ^ added - - // Equivalent to this verbose version: - let qty = match item_quantity.parse::() { - Ok(v) => v, - Err(e) => return Err(e), - }; - - Ok(qty * cost_per_item + processing_fee) -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - use std::num::IntErrorKind; - - #[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().kind(), - &IntErrorKind::InvalidDigit, - ); - } -} diff --git a/rustlings/solutions/13_error_handling/errors3.rs b/rustlings/solutions/13_error_handling/errors3.rs deleted file mode 100644 index 63f4aba..0000000 --- a/rustlings/solutions/13_error_handling/errors3.rs +++ /dev/null @@ -1,32 +0,0 @@ -// 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? - -use std::num::ParseIntError; - -// Don't change this function. -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) -} - -fn main() -> Result<(), ParseIntError> { - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ added - 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."); - } - - // Added this line to return the `Ok` variant of the expected `Result`. - Ok(()) -} diff --git a/rustlings/solutions/13_error_handling/errors4.rs b/rustlings/solutions/13_error_handling/errors4.rs deleted file mode 100644 index 70c5f1c..0000000 --- a/rustlings/solutions/13_error_handling/errors4.rs +++ /dev/null @@ -1,42 +0,0 @@ -use std::cmp::Ordering; - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value.cmp(&0) { - Ordering::Less => Err(CreationError::Negative), - Ordering::Equal => Err(CreationError::Zero), - Ordering::Greater => Ok(Self(value as u64)), - } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_creation() { - assert_eq!( - PositiveNonzeroInteger::new(10), - Ok(PositiveNonzeroInteger(10)), - ); - assert_eq!( - PositiveNonzeroInteger::new(-10), - Err(CreationError::Negative), - ); - assert_eq!(PositiveNonzeroInteger::new(0), Err(CreationError::Zero)); - } -} diff --git a/rustlings/solutions/13_error_handling/errors5.rs b/rustlings/solutions/13_error_handling/errors5.rs deleted file mode 100644 index c1424ee..0000000 --- a/rustlings/solutions/13_error_handling/errors5.rs +++ /dev/null @@ -1,54 +0,0 @@ -// This exercise is an altered version of the `errors4` exercise. It 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. -// -// 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`. - -use std::error::Error; -use std::fmt; - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -// This is required so that `CreationError` can implement `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 for CreationError {} - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - 0 => Err(CreationError::Zero), - x => Ok(PositiveNonzeroInteger(x as u64)), - } - } -} - -fn main() -> Result<(), Box> { - let pretend_user_input = "42"; - let x: i64 = pretend_user_input.parse()?; - println!("output={:?}", PositiveNonzeroInteger::new(x)?); - Ok(()) -} diff --git a/rustlings/solutions/13_error_handling/errors6.rs b/rustlings/solutions/13_error_handling/errors6.rs deleted file mode 100644 index ce18073..0000000 --- a/rustlings/solutions/13_error_handling/errors6.rs +++ /dev/null @@ -1,106 +0,0 @@ -// 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. - -use std::num::ParseIntError; - -#[derive(PartialEq, Debug)] -enum CreationError { - Negative, - Zero, -} - -// A custom error type that we will be using in `PositiveNonzeroInteger::parse`. -#[derive(PartialEq, Debug)] -enum ParsePosNonzeroError { - Creation(CreationError), - ParseInt(ParseIntError), -} - -impl ParsePosNonzeroError { - fn from_creation(err: CreationError) -> Self { - Self::Creation(err) - } - - fn from_parse_int(err: ParseIntError) -> Self { - Self::ParseInt(err) - } -} - -// As an alternative solution, implementing the `From` trait allows for the -// automatic conversion from a `ParseIntError` into a `ParsePosNonzeroError` -// using the `?` operator, without the need to call `map_err`. -// -// ``` -// let x: i64 = s.parse()?; -// ``` -// -// Traits like `From` will be dealt with in later exercises. -impl From for ParsePosNonzeroError { - fn from(err: ParseIntError) -> Self { - ParsePosNonzeroError::ParseInt(err) - } -} - -#[derive(PartialEq, Debug)] -struct PositiveNonzeroInteger(u64); - -impl PositiveNonzeroInteger { - fn new(value: i64) -> Result { - match value { - x if x < 0 => Err(CreationError::Negative), - 0 => Err(CreationError::Zero), - x => Ok(Self(x as u64)), - } - } - - fn parse(s: &str) -> Result { - // Return an appropriate error instead of panicking when `parse()` - // returns an error. - let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parse_int)?; - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - Self::new(x).map_err(ParsePosNonzeroError::from_creation) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_parse_error() { - assert!(matches!( - PositiveNonzeroInteger::parse("not a number"), - Err(ParsePosNonzeroError::ParseInt(_)), - )); - } - - #[test] - fn test_negative() { - assert_eq!( - PositiveNonzeroInteger::parse("-555"), - Err(ParsePosNonzeroError::Creation(CreationError::Negative)), - ); - } - - #[test] - fn test_zero() { - assert_eq!( - PositiveNonzeroInteger::parse("0"), - Err(ParsePosNonzeroError::Creation(CreationError::Zero)), - ); - } - - #[test] - fn test_positive() { - let x = PositiveNonzeroInteger::new(42).unwrap(); - assert_eq!(x.0, 42); - assert_eq!(PositiveNonzeroInteger::parse("42"), Ok(x)); - } -} diff --git a/rustlings/solutions/14_generics/generics1.rs b/rustlings/solutions/14_generics/generics1.rs deleted file mode 100644 index e2195fd..0000000 --- a/rustlings/solutions/14_generics/generics1.rs +++ /dev/null @@ -1,17 +0,0 @@ -// `Vec` is generic over the type `T`. In most cases, the compiler is able to -// infer `T`, for example after pushing a value with a concrete type to the vector. -// But in this exercise, the compiler needs some help through a type annotation. - -fn main() { - // `u8` and `i8` can both be converted to `i16`. - let mut numbers: Vec = Vec::new(); - // ^^^^^^^^^^ added - - // Don't change the lines below. - let n1: u8 = 42; - numbers.push(n1.into()); - let n2: i8 = -1; - numbers.push(n2.into()); - - println!("{numbers:?}"); -} diff --git a/rustlings/solutions/14_generics/generics2.rs b/rustlings/solutions/14_generics/generics2.rs deleted file mode 100644 index 14f3f7a..0000000 --- a/rustlings/solutions/14_generics/generics2.rs +++ /dev/null @@ -1,28 +0,0 @@ -struct Wrapper { - value: T, -} - -impl Wrapper { - fn new(value: T) -> Self { - Wrapper { value } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/solutions/15_traits/traits1.rs b/rustlings/solutions/15_traits/traits1.rs deleted file mode 100644 index 790873f..0000000 --- a/rustlings/solutions/15_traits/traits1.rs +++ /dev/null @@ -1,32 +0,0 @@ -// The trait `AppendBar` has only one function which appends "Bar" to any object -// implementing this trait. -trait AppendBar { - fn append_bar(self) -> Self; -} - -impl AppendBar for String { - fn append_bar(self) -> Self { - self + "Bar" - } -} - -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(), "FooBar"); - } - - #[test] - fn is_bar_bar() { - assert_eq!(String::from("").append_bar().append_bar(), "BarBar"); - } -} diff --git a/rustlings/solutions/15_traits/traits2.rs b/rustlings/solutions/15_traits/traits2.rs deleted file mode 100644 index 0db93e0..0000000 --- a/rustlings/solutions/15_traits/traits2.rs +++ /dev/null @@ -1,27 +0,0 @@ -trait AppendBar { - fn append_bar(self) -> Self; -} - -impl AppendBar for Vec { - fn append_bar(mut self) -> Self { - // ^^^ this is important - self.push(String::from("Bar")); - self - } -} - -fn main() { - // You can optionally experiment here. -} - -#[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(), "Bar"); - assert_eq!(foo.pop().unwrap(), "Foo"); - } -} diff --git a/rustlings/solutions/15_traits/traits3.rs b/rustlings/solutions/15_traits/traits3.rs deleted file mode 100644 index 3d8ec85..0000000 --- a/rustlings/solutions/15_traits/traits3.rs +++ /dev/null @@ -1,36 +0,0 @@ -trait Licensed { - fn licensing_info(&self) -> String { - "Default license".to_string() - } -} - -struct SomeSoftware { - version_number: i32, -} - -struct OtherSoftware { - version_number: String, -} - -impl Licensed for SomeSoftware {} -impl Licensed for OtherSoftware {} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn is_licensing_info_the_same() { - let licensing_info = "Default license"; - 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/rustlings/solutions/15_traits/traits4.rs b/rustlings/solutions/15_traits/traits4.rs deleted file mode 100644 index 3675b8d..0000000 --- a/rustlings/solutions/15_traits/traits4.rs +++ /dev/null @@ -1,35 +0,0 @@ -trait Licensed { - fn licensing_info(&self) -> String { - "Default license".to_string() - } -} - -struct SomeSoftware; -struct OtherSoftware; - -impl Licensed for SomeSoftware {} -impl Licensed for OtherSoftware {} - -fn compare_license_types(software1: impl Licensed, software2: impl Licensed) -> bool { - // ^^^^^^^^^^^^^ ^^^^^^^^^^^^^ - software1.licensing_info() == software2.licensing_info() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn compare_license_information() { - assert!(compare_license_types(SomeSoftware, OtherSoftware)); - } - - #[test] - fn compare_license_information_backwards() { - assert!(compare_license_types(OtherSoftware, SomeSoftware)); - } -} diff --git a/rustlings/solutions/15_traits/traits5.rs b/rustlings/solutions/15_traits/traits5.rs deleted file mode 100644 index 1fb426a..0000000 --- a/rustlings/solutions/15_traits/traits5.rs +++ /dev/null @@ -1,39 +0,0 @@ -trait SomeTrait { - fn some_function(&self) -> bool { - true - } -} - -trait OtherTrait { - fn other_function(&self) -> bool { - true - } -} - -struct SomeStruct; -impl SomeTrait for SomeStruct {} -impl OtherTrait for SomeStruct {} - -struct OtherStruct; -impl SomeTrait for OtherStruct {} -impl OtherTrait for OtherStruct {} - -fn some_func(item: impl SomeTrait + OtherTrait) -> bool { - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - item.some_function() && item.other_function() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_some_func() { - assert!(some_func(SomeStruct)); - assert!(some_func(OtherStruct)); - } -} diff --git a/rustlings/solutions/16_lifetimes/lifetimes1.rs b/rustlings/solutions/16_lifetimes/lifetimes1.rs deleted file mode 100644 index 4f56834..0000000 --- a/rustlings/solutions/16_lifetimes/lifetimes1.rs +++ /dev/null @@ -1,24 +0,0 @@ -// 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? - -fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { - // ^^^^ ^^ ^^ ^^ - if x.len() > y.len() { x } else { y } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_longest() { - assert_eq!(longest("abcd", "123"), "abcd"); - assert_eq!(longest("abc", "1234"), "1234"); - } -} diff --git a/rustlings/solutions/16_lifetimes/lifetimes2.rs b/rustlings/solutions/16_lifetimes/lifetimes2.rs deleted file mode 100644 index 3ca4909..0000000 --- a/rustlings/solutions/16_lifetimes/lifetimes2.rs +++ /dev/null @@ -1,29 +0,0 @@ -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"); - // Solution1: You can move `strings2` out of the inner block so that it is - // not dropped before the print statement. - let string2 = String::from("xyz"); - let result; - { - result = longest(&string1, &string2); - } - println!("The longest string is '{result}'"); - // `string2` dropped at the end of the function. - - // ========================================================================= - - let string1 = String::from("long string is long"); - let result; - { - let string2 = String::from("xyz"); - result = longest(&string1, &string2); - // Solution2: You can move the print statement into the inner block so - // that it is executed before `string2` is dropped. - println!("The longest string is '{result}'"); - // `string2` dropped here (end of the inner scope). - } -} diff --git a/rustlings/solutions/16_lifetimes/lifetimes3.rs b/rustlings/solutions/16_lifetimes/lifetimes3.rs deleted file mode 100644 index 16a5a68..0000000 --- a/rustlings/solutions/16_lifetimes/lifetimes3.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Lifetimes are also needed when structs hold references. - -struct Book<'a> { - // ^^^^ added a lifetime annotation - author: &'a str, - // ^^ - title: &'a str, - // ^^ -} - -fn main() { - let book = Book { - author: "George Orwell", - title: "1984", - }; - - println!("{} by {}", book.title, book.author); -} diff --git a/rustlings/solutions/17_tests/tests1.rs b/rustlings/solutions/17_tests/tests1.rs deleted file mode 100644 index c52b8b1..0000000 --- a/rustlings/solutions/17_tests/tests1.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Tests are important to ensure that your code does what you think it should -// do. - -fn is_even(n: i64) -> bool { - n % 2 == 0 -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - // When writing unit tests, it is common to import everything from the outer - // module (`super`) using a wildcard. - use super::*; - - #[test] - fn you_can_assert() { - assert!(is_even(0)); - assert!(!is_even(-1)); - // ^ You can assert `false` using the negation operator `!`. - } -} diff --git a/rustlings/solutions/17_tests/tests2.rs b/rustlings/solutions/17_tests/tests2.rs deleted file mode 100644 index 39a0005..0000000 --- a/rustlings/solutions/17_tests/tests2.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Calculates the power of 2 using a bit shift. -// `1 << n` is equivalent to "2 to the power of n". -fn power_of_2(n: u8) -> u64 { - 1 << n -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn you_can_assert_eq() { - assert_eq!(power_of_2(0), 1); - assert_eq!(power_of_2(1), 2); - assert_eq!(power_of_2(2), 4); - assert_eq!(power_of_2(3), 8); - } -} diff --git a/rustlings/solutions/17_tests/tests3.rs b/rustlings/solutions/17_tests/tests3.rs deleted file mode 100644 index 487fdc6..0000000 --- a/rustlings/solutions/17_tests/tests3.rs +++ /dev/null @@ -1,45 +0,0 @@ -struct Rectangle { - width: i32, - height: i32, -} - -impl Rectangle { - // Don't change this function. - fn new(width: i32, height: i32) -> Self { - if width <= 0 || height <= 0 { - // Returning a `Result` would be better here. But we want to learn - // how to test functions that can panic. - panic!("Rectangle width and height must be positive"); - } - - Rectangle { width, height } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn correct_width_and_height() { - let rect = Rectangle::new(10, 20); - assert_eq!(rect.width, 10); // Check width - assert_eq!(rect.height, 20); // Check height - } - - #[test] - #[should_panic] // Added this attribute to check that the test panics. - fn negative_width() { - let _rect = Rectangle::new(-10, 10); - } - - #[test] - #[should_panic] // Added this attribute to check that the test panics. - fn negative_height() { - let _rect = Rectangle::new(10, -10); - } -} diff --git a/rustlings/solutions/18_iterators/iterators1.rs b/rustlings/solutions/18_iterators/iterators1.rs deleted file mode 100644 index 93a6008..0000000 --- a/rustlings/solutions/18_iterators/iterators1.rs +++ /dev/null @@ -1,26 +0,0 @@ -// 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. - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - #[test] - fn iterators() { - let my_fav_fruits = ["banana", "custard apple", "avocado", "peach", "raspberry"]; - - // Create an iterator over the array. - let mut fav_fruits_iterator = my_fav_fruits.iter(); - - assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); - assert_eq!(fav_fruits_iterator.next(), Some(&"custard apple")); - assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); - assert_eq!(fav_fruits_iterator.next(), Some(&"peach")); - assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); - assert_eq!(fav_fruits_iterator.next(), None); - // ^^^^ reached the end - } -} diff --git a/rustlings/solutions/18_iterators/iterators2.rs b/rustlings/solutions/18_iterators/iterators2.rs deleted file mode 100644 index db05f29..0000000 --- a/rustlings/solutions/18_iterators/iterators2.rs +++ /dev/null @@ -1,56 +0,0 @@ -// In this exercise, you'll learn some of the unique advantages that iterators -// can offer. - -// "hello" -> "Hello" -fn capitalize_first(input: &str) -> String { - let mut chars = input.chars(); - match chars.next() { - None => String::new(), - Some(first) => first.to_uppercase().to_string() + chars.as_str(), - } -} - -// Apply the `capitalize_first` function to a slice of string slices. -// Return a vector of strings. -// ["hello", "world"] -> ["Hello", "World"] -fn capitalize_words_vector(words: &[&str]) -> Vec { - words.iter().map(|word| capitalize_first(word)).collect() -} - -// Apply the `capitalize_first` function again to a slice of string -// slices. Return a single string. -// ["hello", " ", "world"] -> "Hello World" -fn capitalize_words_string(words: &[&str]) -> String { - words.iter().map(|word| capitalize_first(word)).collect() -} - -fn main() { - // You can optionally experiment here. -} - -#[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/rustlings/solutions/18_iterators/iterators3.rs b/rustlings/solutions/18_iterators/iterators3.rs deleted file mode 100644 index 1d5d67f..0000000 --- a/rustlings/solutions/18_iterators/iterators3.rs +++ /dev/null @@ -1,88 +0,0 @@ -#[derive(Debug, PartialEq, Eq)] -enum DivisionError { - // Example: 42 / 0 - DivideByZero, - // Only case for `i64`: `i64::MIN / -1` because the result is `i64::MAX + 1` - IntegerOverflow, - // Example: 5 / 2 = 2.5 - NotDivisible, -} - -fn divide(a: i64, b: i64) -> Result { - if b == 0 { - return Err(DivisionError::DivideByZero); - } - - if a == i64::MIN && b == -1 { - return Err(DivisionError::IntegerOverflow); - } - - if a % b != 0 { - return Err(DivisionError::NotDivisible); - } - - Ok(a / b) -} - -fn result_with_list() -> Result, DivisionError> { - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - let numbers = [27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); - // Collects to the expected return type. Returns the first error in the - // division results (if one exists). - division_results.collect() -} - -fn list_of_results() -> Vec> { - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - let numbers = [27, 297, 38502, 81]; - let division_results = numbers.into_iter().map(|n| divide(n, 27)); - // Collects to the expected return type. - division_results.collect() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_success() { - assert_eq!(divide(81, 9), Ok(9)); - assert_eq!(divide(81, -1), Ok(-81)); - assert_eq!(divide(i64::MIN, i64::MIN), Ok(1)); - } - - #[test] - fn test_divide_by_0() { - assert_eq!(divide(81, 0), Err(DivisionError::DivideByZero)); - } - - #[test] - fn test_integer_overflow() { - assert_eq!(divide(i64::MIN, -1), Err(DivisionError::IntegerOverflow)); - } - - #[test] - fn test_not_divisible() { - assert_eq!(divide(81, 6), Err(DivisionError::NotDivisible)); - } - - #[test] - fn test_divide_0_by_something() { - assert_eq!(divide(0, 81), Ok(0)); - } - - #[test] - fn test_result_with_list() { - assert_eq!(result_with_list().unwrap(), [1, 11, 1426, 3]); - } - - #[test] - fn test_list_of_results() { - assert_eq!(list_of_results(), [Ok(1), Ok(11), Ok(1426), Ok(3)]); - } -} diff --git a/rustlings/solutions/18_iterators/iterators4.rs b/rustlings/solutions/18_iterators/iterators4.rs deleted file mode 100644 index 4168835..0000000 --- a/rustlings/solutions/18_iterators/iterators4.rs +++ /dev/null @@ -1,72 +0,0 @@ -// 3 possible solutions are presented. - -// With `for` loop and a mutable variable. -fn factorial_for(num: u64) -> u64 { - let mut result = 1; - - for x in 2..=num { - result *= x; - } - - result -} - -// Equivalent to `factorial_for` but shorter and without a `for` loop and -// mutable variables. -fn factorial_fold(num: u64) -> u64 { - // Case num==0: The iterator 2..=0 is empty - // -> The initial value of `fold` is returned which is 1. - // Case num==1: The iterator 2..=1 is also empty - // -> The initial value 1 is returned. - // Case num==2: The iterator 2..=2 contains one element - // -> The initial value 1 is multiplied by 2 and the result - // is returned. - // Case num==3: The iterator 2..=3 contains 2 elements - // -> 1 * 2 is calculated, then the result 2 is multiplied by - // the second element 3 so the result 6 is returned. - // And so on… - #[allow(clippy::unnecessary_fold)] - (2..=num).fold(1, |acc, x| acc * x) -} - -// Equivalent to `factorial_fold` but with a built-in method that is suggested -// by Clippy. -fn factorial_product(num: u64) -> u64 { - (2..=num).product() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn factorial_of_0() { - assert_eq!(factorial_for(0), 1); - assert_eq!(factorial_fold(0), 1); - assert_eq!(factorial_product(0), 1); - } - - #[test] - fn factorial_of_1() { - assert_eq!(factorial_for(1), 1); - assert_eq!(factorial_fold(1), 1); - assert_eq!(factorial_product(1), 1); - } - #[test] - fn factorial_of_2() { - assert_eq!(factorial_for(2), 2); - assert_eq!(factorial_fold(2), 2); - assert_eq!(factorial_product(2), 2); - } - - #[test] - fn factorial_of_4() { - assert_eq!(factorial_for(4), 24); - assert_eq!(factorial_fold(4), 24); - assert_eq!(factorial_product(4), 24); - } -} diff --git a/rustlings/solutions/18_iterators/iterators5.rs b/rustlings/solutions/18_iterators/iterators5.rs deleted file mode 100644 index 067a117..0000000 --- a/rustlings/solutions/18_iterators/iterators5.rs +++ /dev/null @@ -1,168 +0,0 @@ -// 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 to not use imperative loops (for/while). - -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 hash map with `String` keys and `Progress` values. - // map = { "variables1": Complete, "from_str": None, … } - map.values().filter(|val| **val == value).count() -} - -fn count_collection_for(collection: &[HashMap], value: Progress) -> usize { - let mut count = 0; - for map in collection { - count += count_for(map, value); - } - count -} - -fn count_collection_iterator(collection: &[HashMap], value: Progress) -> usize { - // `collection` is a slice of hash maps. - // collection = [{ "variables1": Complete, "from_str": None, … }, - // { "variables2": Complete, … }, … ] - collection - .iter() - .map(|map| count_iterator(map, value)) - .sum() -} - -// Equivalent to `count_collection_iterator` and `count_iterator`, iterating as -// if the collection was a single container instead of a container of containers -// (and more accurately, a single iterator instead of an iterator of iterators). -fn count_collection_iterator_flat( - collection: &[HashMap], - value: Progress, -) -> usize { - // `collection` is a slice of hash maps. - // collection = [{ "variables1": Complete, "from_str": None, … }, - // { "variables2": Complete, … }, … ] - collection - .iter() - .flat_map(HashMap::values) // or just `.flatten()` when wanting the default iterator (`HashMap::iter`) - .filter(|val| **val == value) - .count() -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - use Progress::*; - - fn get_map() -> HashMap { - 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> { - 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] - } - - #[test] - fn count_complete() { - let map = get_map(); - assert_eq!(count_iterator(&map, Complete), 3); - } - - #[test] - fn count_some() { - let map = get_map(); - assert_eq!(count_iterator(&map, Some), 1); - } - - #[test] - fn count_none() { - let map = get_map(); - assert_eq!(count_iterator(&map, None), 2); - } - - #[test] - fn count_complete_equals_for() { - let map = get_map(); - let progress_states = [Complete, Some, 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!(count_collection_iterator(&collection, Complete), 6); - assert_eq!(count_collection_iterator_flat(&collection, Complete), 6); - } - - #[test] - fn count_collection_some() { - let collection = get_vec_map(); - assert_eq!(count_collection_iterator(&collection, Some), 1); - assert_eq!(count_collection_iterator_flat(&collection, Some), 1); - } - - #[test] - fn count_collection_none() { - let collection = get_vec_map(); - assert_eq!(count_collection_iterator(&collection, None), 4); - assert_eq!(count_collection_iterator_flat(&collection, None), 4); - } - - #[test] - fn count_collection_equals_for() { - let collection = get_vec_map(); - let progress_states = [Complete, Some, None]; - - for progress_state in progress_states { - assert_eq!( - count_collection_for(&collection, progress_state), - count_collection_iterator(&collection, progress_state), - ); - assert_eq!( - count_collection_for(&collection, progress_state), - count_collection_iterator_flat(&collection, progress_state), - ); - } - } -} diff --git a/rustlings/solutions/19_smart_pointers/arc1.rs b/rustlings/solutions/19_smart_pointers/arc1.rs deleted file mode 100644 index bd76189..0000000 --- a/rustlings/solutions/19_smart_pointers/arc1.rs +++ /dev/null @@ -1,45 +0,0 @@ -// In this exercise, we are given a `Vec` of `u32` called `numbers` with values -// ranging from 0 to 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, … -// -// Each thread should own a reference-counting pointer to the vector of -// numbers. But `Rc` isn't thread-safe. Therefore, we need to use `Arc`. -// -// Don't get distracted by how threads are spawned and joined. We will practice -// that later in the exercises about threads. - -// Don't change the lines below. -#![forbid(unused_imports)] -use std::{sync::Arc, thread}; - -fn main() { - let numbers: Vec<_> = (0..100u32).collect(); - - let shared_numbers = Arc::new(numbers); - // ^^^^^^^^^^^^^^^^^ - - let mut join_handles = Vec::new(); - - for offset in 0..8 { - let child_numbers = Arc::clone(&shared_numbers); - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - - let handle = thread::spawn(move || { - let sum: u32 = child_numbers.iter().filter(|&&n| n % 8 == offset).sum(); - println!("Sum of offset {offset} is {sum}"); - }); - - join_handles.push(handle); - } - - for handle in join_handles.into_iter() { - handle.join().unwrap(); - } -} diff --git a/rustlings/solutions/19_smart_pointers/box1.rs b/rustlings/solutions/19_smart_pointers/box1.rs deleted file mode 100644 index 189cc56..0000000 --- a/rustlings/solutions/19_smart_pointers/box1.rs +++ /dev/null @@ -1,47 +0,0 @@ -// 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`. - -#[derive(PartialEq, Debug)] -enum List { - Cons(i32, Box), - Nil, -} - -fn create_empty_list() -> List { - List::Nil -} - -fn create_non_empty_list() -> List { - List::Cons(42, Box::new(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(), - ); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_create_empty_list() { - assert_eq!(create_empty_list(), List::Nil); - } - - #[test] - fn test_create_non_empty_list() { - assert_ne!(create_empty_list(), create_non_empty_list()); - } -} diff --git a/rustlings/solutions/19_smart_pointers/cow1.rs b/rustlings/solutions/19_smart_pointers/cow1.rs deleted file mode 100644 index 461143b..0000000 --- a/rustlings/solutions/19_smart_pointers/cow1.rs +++ /dev/null @@ -1,69 +0,0 @@ -// This exercise explores the `Cow` (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. - -use std::borrow::Cow; - -fn abs_all(input: &mut Cow<[i32]>) { - for ind in 0..input.len() { - let value = input[ind]; - if value < 0 { - // Clones into a vector if not already owned. - input.to_mut()[ind] = -value; - } - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reference_mutation() { - // Clone occurs because `input` needs to be mutated. - let vec = vec![-1, 0, 1]; - let mut input = Cow::from(&vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Owned(_))); - } - - #[test] - fn reference_no_mutation() { - // No clone occurs because `input` doesn't need to be mutated. - let vec = vec![0, 1, 2]; - let mut input = Cow::from(&vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Borrowed(_))); - // ^^^^^^^^^^^^^^^^ - } - - #[test] - fn owned_no_mutation() { - // We can also pass `vec` without `&` so `Cow` owns it directly. In this - // case, no mutation occurs (all numbers are already absolute) and thus - // also no clone. But the result is still owned because it was never - // borrowed or mutated. - let vec = vec![0, 1, 2]; - let mut input = Cow::from(vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Owned(_))); - // ^^^^^^^^^^^^^ - } - - #[test] - fn owned_mutation() { - // Of course this is also the case if a mutation does occur (not all - // numbers are absolute). In this case, the call to `to_mut()` in the - // `abs_all` function returns a reference to the same data as before. - let vec = vec![-1, 0, 1]; - let mut input = Cow::from(vec); - abs_all(&mut input); - assert!(matches!(input, Cow::Owned(_))); - // ^^^^^^^^^^^^^ - } -} diff --git a/rustlings/solutions/19_smart_pointers/rc1.rs b/rustlings/solutions/19_smart_pointers/rc1.rs deleted file mode 100644 index edf40eb..0000000 --- a/rustlings/solutions/19_smart_pointers/rc1.rs +++ /dev/null @@ -1,102 +0,0 @@ -// 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 `Planet`s. The planets take ownership of the sun, indicating that -// they revolve around the sun. - -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:?}!"); - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn rc1() { - 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(); - - let saturn = Planet::Saturn(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 7 references - saturn.details(); - - let uranus = Planet::Uranus(Rc::clone(&sun)); - println!("reference count = {}", Rc::strong_count(&sun)); // 8 references - uranus.details(); - - let neptune = Planet::Neptune(Rc::clone(&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 - - drop(earth); - println!("reference count = {}", Rc::strong_count(&sun)); // 3 references - - drop(venus); - println!("reference count = {}", Rc::strong_count(&sun)); // 2 references - - drop(mercury); - println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference - - assert_eq!(Rc::strong_count(&sun), 1); - } -} diff --git a/rustlings/solutions/20_threads/threads1.rs b/rustlings/solutions/20_threads/threads1.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/20_threads/threads1.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/20_threads/threads2.rs b/rustlings/solutions/20_threads/threads2.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/20_threads/threads2.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/20_threads/threads3.rs b/rustlings/solutions/20_threads/threads3.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/20_threads/threads3.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/21_macros/macros1.rs b/rustlings/solutions/21_macros/macros1.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/21_macros/macros1.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/21_macros/macros2.rs b/rustlings/solutions/21_macros/macros2.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/21_macros/macros2.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/21_macros/macros3.rs b/rustlings/solutions/21_macros/macros3.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/21_macros/macros3.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/21_macros/macros4.rs b/rustlings/solutions/21_macros/macros4.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/21_macros/macros4.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/22_clippy/clippy1.rs b/rustlings/solutions/22_clippy/clippy1.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/22_clippy/clippy1.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/22_clippy/clippy2.rs b/rustlings/solutions/22_clippy/clippy2.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/22_clippy/clippy2.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/22_clippy/clippy3.rs b/rustlings/solutions/22_clippy/clippy3.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/22_clippy/clippy3.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/23_conversions/as_ref_mut.rs b/rustlings/solutions/23_conversions/as_ref_mut.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/23_conversions/as_ref_mut.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/23_conversions/from_into.rs b/rustlings/solutions/23_conversions/from_into.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/23_conversions/from_into.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/23_conversions/from_str.rs b/rustlings/solutions/23_conversions/from_str.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/23_conversions/from_str.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/23_conversions/try_from_into.rs b/rustlings/solutions/23_conversions/try_from_into.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/23_conversions/try_from_into.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/23_conversions/using_as.rs b/rustlings/solutions/23_conversions/using_as.rs deleted file mode 100644 index dcf2377..0000000 --- a/rustlings/solutions/23_conversions/using_as.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - // DON'T EDIT THIS SOLUTION FILE! - // It will be automatically filled after you finish the exercise. -} diff --git a/rustlings/solutions/README.md b/rustlings/solutions/README.md deleted file mode 100644 index 5b5176b..0000000 --- a/rustlings/solutions/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Official Rustlings solutions - -Before you finish an exercise, its solution file will only contain an empty `main` function. -The content of this file will be automatically replaced by the actual solution once you finish the exercise. - -Note that these solutions are often only _one possibility_ to solve an exercise. diff --git a/rustlings/solutions/quizzes/quiz1.rs b/rustlings/solutions/quizzes/quiz1.rs deleted file mode 100644 index 5503c8c..0000000 --- a/rustlings/solutions/quizzes/quiz1.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Mary is buying apples. The price of an apple is calculated as follows: -// - An apple costs 2 rustbucks. -// - However, if Mary buys more than 40 apples, the price of each apple in the -// entire order is reduced to only 1 rustbuck! - -fn calculate_price_of_apples(n_apples: u64) -> u64 { - if n_apples > 40 { - n_apples - } else { - 2 * n_apples - } -} - -fn main() { - // You can optionally experiment here. -} - -// Don't change the tests! -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn verify_test() { - assert_eq!(calculate_price_of_apples(35), 70); - assert_eq!(calculate_price_of_apples(40), 80); - assert_eq!(calculate_price_of_apples(41), 41); - assert_eq!(calculate_price_of_apples(65), 65); - } -} diff --git a/rustlings/solutions/quizzes/quiz2.rs b/rustlings/solutions/quizzes/quiz2.rs deleted file mode 100644 index 8b073b1..0000000 --- a/rustlings/solutions/quizzes/quiz2.rs +++ /dev/null @@ -1,90 +0,0 @@ -// Let's build a little machine in the form of a function. As input, we're going -// to give a list of strings and commands. These commands determine what action -// is going to be applied to the string. It can either be: -// - Uppercase the string -// - Trim the string -// - Append "bar" to the string a specified amount of times -// -// The exact form of this will be: -// - The input is going to be a vector of 2-length tuples, -// the first element is the string, the second one is the command. -// - The output element is going to be a vector of strings. - -enum Command { - Uppercase, - Trim, - Append(usize), -} - -mod my_module { - use super::Command; - - // The solution with a loop. Check out `transformer_iter` for a version - // with iterators. - pub fn transformer(input: Vec<(String, Command)>) -> Vec { - let mut output = Vec::new(); - - for (string, command) in input { - // Create the new string. - let new_string = match command { - Command::Uppercase => string.to_uppercase(), - Command::Trim => string.trim().to_string(), - Command::Append(n) => string + &"bar".repeat(n), - }; - - // Push the new string to the output vector. - output.push(new_string); - } - - output - } - - // Equivalent to `transform` but uses an iterator instead of a loop for - // comparison. Don't worry, we will practice iterators later ;) - pub fn transformer_iter(input: Vec<(String, Command)>) -> Vec { - input - .into_iter() - .map(|(string, command)| match command { - Command::Uppercase => string.to_uppercase(), - Command::Trim => string.trim().to_string(), - Command::Append(n) => string + &"bar".repeat(n), - }) - .collect() - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - // Import `transformer`. - use super::my_module::transformer; - - use super::Command; - use super::my_module::transformer_iter; - - #[test] - fn it_works() { - for transformer in [transformer, transformer_iter] { - let input = vec![ - ("hello".to_string(), Command::Uppercase), - (" all roads lead to rome! ".to_string(), Command::Trim), - ("foo".to_string(), Command::Append(1)), - ("bar".to_string(), Command::Append(5)), - ]; - let output = transformer(input); - - assert_eq!( - output, - [ - "HELLO", - "all roads lead to rome!", - "foobar", - "barbarbarbarbarbar", - ] - ); - } - } -} diff --git a/rustlings/solutions/quizzes/quiz3.rs b/rustlings/solutions/quizzes/quiz3.rs deleted file mode 100644 index 7b91278..0000000 --- a/rustlings/solutions/quizzes/quiz3.rs +++ /dev/null @@ -1,65 +0,0 @@ -// An imaginary magical school has a new report card generation system written -// in Rust! Currently, the system only supports creating report cards where the -// student's grade is represented numerically (e.g. 1.0 -> 5.5). However, the -// school also issues alphabetical grades (A+ -> F-) and needs to be able to -// print both types of report card! -// -// Make the necessary code changes in the struct `ReportCard` and the impl -// block to support alphabetical report cards in addition to numerical ones. - -use std::fmt::Display; - -// Make the struct generic over `T`. -struct ReportCard { - // ^^^ - grade: T, - // ^ - student_name: String, - student_age: u8, -} - -// To be able to print the grade, it has to implement the `Display` trait. -impl ReportCard { - // ^^^^^^^ require that `T` implements `Display`. - fn print(&self) -> String { - format!( - "{} ({}) - achieved a grade of {}", - &self.student_name, &self.student_age, &self.grade, - ) - } -} - -fn main() { - // You can optionally experiment here. -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn generate_numeric_report_card() { - let report_card = ReportCard { - grade: 2.1, - student_name: "Tom Wriggle".to_string(), - student_age: 12, - }; - assert_eq!( - report_card.print(), - "Tom Wriggle (12) - achieved a grade of 2.1", - ); - } - - #[test] - fn generate_alphabetic_report_card() { - let report_card = ReportCard { - grade: "A+", - student_name: "Gary Plotter".to_string(), - student_age: 11, - }; - assert_eq!( - report_card.print(), - "Gary Plotter (11) - achieved a grade of A+", - ); - } -} -- cgit v1.2.3