From a3e2bc985cacb0e57f5a1ded895af65187a0cf91 Mon Sep 17 00:00:00 2001 From: Tuan-Dat Tran Date: Sun, 1 Sep 2024 19:20:40 +0200 Subject: [PATCH] Initial commit Signed-off-by: Tuan-Dat Tran --- .gitignore | 3 + Cargo.toml | 218 ++++++++++++++++++ exercises/00_intro/README.md | 8 + exercises/00_intro/intro1.rs | 24 ++ exercises/00_intro/intro2.rs | 4 + exercises/01_variables/README.md | 9 + exercises/01_variables/variables1.rs | 6 + exercises/01_variables/variables2.rs | 10 + exercises/01_variables/variables3.rs | 6 + exercises/01_variables/variables4.rs | 8 + exercises/01_variables/variables5.rs | 8 + exercises/01_variables/variables6.rs | 6 + exercises/02_functions/README.md | 8 + exercises/02_functions/functions1.rs | 5 + exercises/02_functions/functions2.rs | 10 + exercises/02_functions/functions3.rs | 10 + exercises/02_functions/functions4.rs | 22 ++ exercises/02_functions/functions5.rs | 9 + exercises/03_if/README.md | 7 + exercises/03_if/if1.rs | 32 +++ exercises/03_if/if2.rs | 35 +++ exercises/03_if/if3.rs | 53 +++++ exercises/04_primitive_types/README.md | 9 + .../04_primitive_types/primitive_types1.rs | 15 ++ .../04_primitive_types/primitive_types2.rs | 28 +++ .../04_primitive_types/primitive_types3.rs | 11 + .../04_primitive_types/primitive_types4.rs | 16 ++ .../04_primitive_types/primitive_types5.rs | 8 + .../04_primitive_types/primitive_types6.rs | 17 ++ exercises/05_vecs/README.md | 17 ++ exercises/05_vecs/vecs1.rs | 24 ++ exercises/05_vecs/vecs2.rs | 60 +++++ exercises/06_move_semantics/README.md | 10 + .../06_move_semantics/move_semantics1.rs | 24 ++ .../06_move_semantics/move_semantics2.rs | 28 +++ .../06_move_semantics/move_semantics3.rs | 22 ++ .../06_move_semantics/move_semantics4.rs | 18 ++ .../06_move_semantics/move_semantics5.rs | 24 ++ exercises/07_structs/README.md | 8 + exercises/07_structs/structs1.rs | 47 ++++ exercises/07_structs/structs2.rs | 47 ++++ exercises/07_structs/structs3.rs | 87 +++++++ exercises/08_enums/README.md | 10 + exercises/08_enums/enums1.rs | 12 + exercises/08_enums/enums2.rs | 35 +++ exercises/08_enums/enums3.rs | 84 +++++++ exercises/09_strings/README.md | 9 + exercises/09_strings/strings1.rs | 9 + exercises/09_strings/strings2.rs | 14 ++ exercises/09_strings/strings3.rs | 45 ++++ exercises/09_strings/strings4.rs | 37 +++ exercises/10_modules/README.md | 7 + exercises/10_modules/modules1.rs | 16 ++ exercises/10_modules/modules2.rs | 27 +++ exercises/10_modules/modules3.rs | 13 ++ exercises/11_hashmaps/README.md | 12 + exercises/11_hashmaps/hashmaps1.rs | 40 ++++ exercises/11_hashmaps/hashmaps2.rs | 97 ++++++++ exercises/11_hashmaps/hashmaps3.rs | 77 +++++++ exercises/12_options/README.md | 21 ++ exercises/12_options/options1.rs | 36 +++ exercises/12_options/options2.rs | 39 ++++ exercises/12_options/options3.rs | 17 ++ exercises/13_error_handling/README.md | 12 + exercises/13_error_handling/errors1.rs | 41 ++++ exercises/13_error_handling/errors2.rs | 50 ++++ exercises/13_error_handling/errors3.rs | 31 +++ exercises/13_error_handling/errors4.rs | 37 +++ exercises/13_error_handling/errors5.rs | 56 +++++ exercises/13_error_handling/errors6.rs | 89 +++++++ exercises/14_generics/README.md | 11 + exercises/14_generics/generics1.rs | 18 ++ exercises/14_generics/generics2.rs | 31 +++ exercises/15_traits/README.md | 19 ++ exercises/15_traits/traits1.rs | 30 +++ exercises/15_traits/traits2.rs | 22 ++ exercises/15_traits/traits3.rs | 40 ++++ exercises/15_traits/traits4.rs | 35 +++ exercises/15_traits/traits5.rs | 39 ++++ exercises/16_lifetimes/README.md | 22 ++ exercises/16_lifetimes/lifetimes1.rs | 28 +++ exercises/16_lifetimes/lifetimes2.rs | 20 ++ exercises/16_lifetimes/lifetimes3.rs | 16 ++ exercises/17_tests/README.md | 7 + exercises/17_tests/tests1.rs | 23 ++ exercises/17_tests/tests2.rs | 23 ++ exercises/17_tests/tests3.rs | 49 ++++ exercises/18_iterators/README.md | 8 + exercises/18_iterators/iterators1.rs | 25 ++ exercises/18_iterators/iterators2.rs | 57 +++++ exercises/18_iterators/iterators3.rs | 73 ++++++ exercises/18_iterators/iterators4.rs | 41 ++++ exercises/18_iterators/iterators5.rs | 153 ++++++++++++ exercises/19_smart_pointers/README.md | 12 + exercises/19_smart_pointers/arc1.rs | 45 ++++ exercises/19_smart_pointers/box1.rs | 50 ++++ exercises/19_smart_pointers/cow1.rs | 69 ++++++ exercises/19_smart_pointers/rc1.rs | 106 +++++++++ exercises/20_threads/README.md | 10 + exercises/20_threads/threads1.rs | 37 +++ exercises/20_threads/threads2.rs | 34 +++ exercises/20_threads/threads3.rs | 60 +++++ exercises/21_macros/README.md | 14 ++ exercises/21_macros/macros1.rs | 10 + exercises/21_macros/macros2.rs | 10 + exercises/21_macros/macros3.rs | 13 ++ exercises/21_macros/macros4.rs | 15 ++ exercises/22_clippy/README.md | 10 + exercises/22_clippy/clippy1.rs | 15 ++ exercises/22_clippy/clippy2.rs | 10 + exercises/22_clippy/clippy3.rs | 27 +++ exercises/23_conversions/README.md | 23 ++ exercises/23_conversions/as_ref_mut.rs | 61 +++++ exercises/23_conversions/from_into.rs | 130 +++++++++++ exercises/23_conversions/from_str.rs | 113 +++++++++ exercises/23_conversions/try_from_into.rs | 177 ++++++++++++++ exercises/23_conversions/using_as.rs | 24 ++ exercises/README.md | 27 +++ exercises/quizzes/README.md | 3 + exercises/quizzes/quiz1.rs | 31 +++ exercises/quizzes/quiz2.rs | 63 +++++ exercises/quizzes/quiz3.rs | 64 +++++ solutions/00_intro/intro1.rs | 4 + solutions/00_intro/intro2.rs | 4 + solutions/01_variables/variables1.rs | 4 + solutions/01_variables/variables2.rs | 4 + solutions/01_variables/variables3.rs | 4 + solutions/01_variables/variables4.rs | 4 + solutions/01_variables/variables5.rs | 4 + solutions/01_variables/variables6.rs | 4 + solutions/02_functions/functions1.rs | 4 + solutions/02_functions/functions2.rs | 4 + solutions/02_functions/functions3.rs | 4 + solutions/02_functions/functions4.rs | 4 + solutions/02_functions/functions5.rs | 4 + solutions/03_if/if1.rs | 4 + solutions/03_if/if2.rs | 4 + solutions/03_if/if3.rs | 4 + .../04_primitive_types/primitive_types1.rs | 4 + .../04_primitive_types/primitive_types2.rs | 4 + .../04_primitive_types/primitive_types3.rs | 4 + .../04_primitive_types/primitive_types4.rs | 4 + .../04_primitive_types/primitive_types5.rs | 4 + .../04_primitive_types/primitive_types6.rs | 4 + solutions/05_vecs/vecs1.rs | 4 + solutions/05_vecs/vecs2.rs | 4 + .../06_move_semantics/move_semantics1.rs | 4 + .../06_move_semantics/move_semantics2.rs | 4 + .../06_move_semantics/move_semantics3.rs | 4 + .../06_move_semantics/move_semantics4.rs | 4 + .../06_move_semantics/move_semantics5.rs | 4 + solutions/07_structs/structs1.rs | 4 + solutions/07_structs/structs2.rs | 4 + solutions/07_structs/structs3.rs | 4 + solutions/08_enums/enums1.rs | 4 + solutions/08_enums/enums2.rs | 4 + solutions/08_enums/enums3.rs | 4 + solutions/09_strings/strings1.rs | 4 + solutions/09_strings/strings2.rs | 4 + solutions/09_strings/strings3.rs | 4 + solutions/09_strings/strings4.rs | 4 + solutions/10_modules/modules1.rs | 4 + solutions/10_modules/modules2.rs | 4 + solutions/10_modules/modules3.rs | 4 + solutions/11_hashmaps/hashmaps1.rs | 4 + solutions/11_hashmaps/hashmaps2.rs | 4 + solutions/11_hashmaps/hashmaps3.rs | 4 + solutions/12_options/options1.rs | 4 + solutions/12_options/options2.rs | 4 + solutions/12_options/options3.rs | 4 + solutions/13_error_handling/errors1.rs | 4 + solutions/13_error_handling/errors2.rs | 4 + solutions/13_error_handling/errors3.rs | 4 + solutions/13_error_handling/errors4.rs | 4 + solutions/13_error_handling/errors5.rs | 4 + solutions/13_error_handling/errors6.rs | 4 + solutions/14_generics/generics1.rs | 4 + solutions/14_generics/generics2.rs | 4 + solutions/15_traits/traits1.rs | 4 + solutions/15_traits/traits2.rs | 4 + solutions/15_traits/traits3.rs | 4 + solutions/15_traits/traits4.rs | 4 + solutions/15_traits/traits5.rs | 4 + solutions/16_lifetimes/lifetimes1.rs | 4 + solutions/16_lifetimes/lifetimes2.rs | 4 + solutions/16_lifetimes/lifetimes3.rs | 4 + solutions/17_tests/tests1.rs | 4 + solutions/17_tests/tests2.rs | 4 + solutions/17_tests/tests3.rs | 4 + solutions/18_iterators/iterators1.rs | 4 + solutions/18_iterators/iterators2.rs | 4 + solutions/18_iterators/iterators3.rs | 4 + solutions/18_iterators/iterators4.rs | 4 + solutions/18_iterators/iterators5.rs | 4 + solutions/19_smart_pointers/arc1.rs | 4 + solutions/19_smart_pointers/box1.rs | 4 + solutions/19_smart_pointers/cow1.rs | 4 + solutions/19_smart_pointers/rc1.rs | 4 + solutions/20_threads/threads1.rs | 4 + solutions/20_threads/threads2.rs | 4 + solutions/20_threads/threads3.rs | 4 + solutions/21_macros/macros1.rs | 4 + solutions/21_macros/macros2.rs | 4 + solutions/21_macros/macros3.rs | 4 + solutions/21_macros/macros4.rs | 4 + solutions/22_clippy/clippy1.rs | 4 + solutions/22_clippy/clippy2.rs | 4 + solutions/22_clippy/clippy3.rs | 4 + solutions/23_conversions/as_ref_mut.rs | 4 + solutions/23_conversions/from_into.rs | 4 + solutions/23_conversions/from_str.rs | 4 + solutions/23_conversions/try_from_into.rs | 4 + solutions/23_conversions/using_as.rs | 4 + solutions/README.md | 6 + solutions/quizzes/quiz1.rs | 4 + solutions/quizzes/quiz2.rs | 4 + solutions/quizzes/quiz3.rs | 4 + 217 files changed, 4429 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 exercises/00_intro/README.md create mode 100644 exercises/00_intro/intro1.rs create mode 100644 exercises/00_intro/intro2.rs create mode 100644 exercises/01_variables/README.md create mode 100644 exercises/01_variables/variables1.rs create mode 100644 exercises/01_variables/variables2.rs create mode 100644 exercises/01_variables/variables3.rs create mode 100644 exercises/01_variables/variables4.rs create mode 100644 exercises/01_variables/variables5.rs create mode 100644 exercises/01_variables/variables6.rs create mode 100644 exercises/02_functions/README.md create mode 100644 exercises/02_functions/functions1.rs create mode 100644 exercises/02_functions/functions2.rs create mode 100644 exercises/02_functions/functions3.rs create mode 100644 exercises/02_functions/functions4.rs create mode 100644 exercises/02_functions/functions5.rs create mode 100644 exercises/03_if/README.md create mode 100644 exercises/03_if/if1.rs create mode 100644 exercises/03_if/if2.rs create mode 100644 exercises/03_if/if3.rs create mode 100644 exercises/04_primitive_types/README.md create mode 100644 exercises/04_primitive_types/primitive_types1.rs create mode 100644 exercises/04_primitive_types/primitive_types2.rs create mode 100644 exercises/04_primitive_types/primitive_types3.rs create mode 100644 exercises/04_primitive_types/primitive_types4.rs create mode 100644 exercises/04_primitive_types/primitive_types5.rs create mode 100644 exercises/04_primitive_types/primitive_types6.rs create mode 100644 exercises/05_vecs/README.md create mode 100644 exercises/05_vecs/vecs1.rs create mode 100644 exercises/05_vecs/vecs2.rs create mode 100644 exercises/06_move_semantics/README.md create mode 100644 exercises/06_move_semantics/move_semantics1.rs create mode 100644 exercises/06_move_semantics/move_semantics2.rs create mode 100644 exercises/06_move_semantics/move_semantics3.rs create mode 100644 exercises/06_move_semantics/move_semantics4.rs create mode 100644 exercises/06_move_semantics/move_semantics5.rs create mode 100644 exercises/07_structs/README.md create mode 100644 exercises/07_structs/structs1.rs create mode 100644 exercises/07_structs/structs2.rs create mode 100644 exercises/07_structs/structs3.rs create mode 100644 exercises/08_enums/README.md create mode 100644 exercises/08_enums/enums1.rs create mode 100644 exercises/08_enums/enums2.rs create mode 100644 exercises/08_enums/enums3.rs create mode 100644 exercises/09_strings/README.md create mode 100644 exercises/09_strings/strings1.rs create mode 100644 exercises/09_strings/strings2.rs create mode 100644 exercises/09_strings/strings3.rs create mode 100644 exercises/09_strings/strings4.rs create mode 100644 exercises/10_modules/README.md create mode 100644 exercises/10_modules/modules1.rs create mode 100644 exercises/10_modules/modules2.rs create mode 100644 exercises/10_modules/modules3.rs create mode 100644 exercises/11_hashmaps/README.md create mode 100644 exercises/11_hashmaps/hashmaps1.rs create mode 100644 exercises/11_hashmaps/hashmaps2.rs create mode 100644 exercises/11_hashmaps/hashmaps3.rs create mode 100644 exercises/12_options/README.md create mode 100644 exercises/12_options/options1.rs create mode 100644 exercises/12_options/options2.rs create mode 100644 exercises/12_options/options3.rs create mode 100644 exercises/13_error_handling/README.md create mode 100644 exercises/13_error_handling/errors1.rs create mode 100644 exercises/13_error_handling/errors2.rs create mode 100644 exercises/13_error_handling/errors3.rs create mode 100644 exercises/13_error_handling/errors4.rs create mode 100644 exercises/13_error_handling/errors5.rs create mode 100644 exercises/13_error_handling/errors6.rs create mode 100644 exercises/14_generics/README.md create mode 100644 exercises/14_generics/generics1.rs create mode 100644 exercises/14_generics/generics2.rs create mode 100644 exercises/15_traits/README.md create mode 100644 exercises/15_traits/traits1.rs create mode 100644 exercises/15_traits/traits2.rs create mode 100644 exercises/15_traits/traits3.rs create mode 100644 exercises/15_traits/traits4.rs create mode 100644 exercises/15_traits/traits5.rs create mode 100644 exercises/16_lifetimes/README.md create mode 100644 exercises/16_lifetimes/lifetimes1.rs create mode 100644 exercises/16_lifetimes/lifetimes2.rs create mode 100644 exercises/16_lifetimes/lifetimes3.rs create mode 100644 exercises/17_tests/README.md create mode 100644 exercises/17_tests/tests1.rs create mode 100644 exercises/17_tests/tests2.rs create mode 100644 exercises/17_tests/tests3.rs create mode 100644 exercises/18_iterators/README.md create mode 100644 exercises/18_iterators/iterators1.rs create mode 100644 exercises/18_iterators/iterators2.rs create mode 100644 exercises/18_iterators/iterators3.rs create mode 100644 exercises/18_iterators/iterators4.rs create mode 100644 exercises/18_iterators/iterators5.rs create mode 100644 exercises/19_smart_pointers/README.md create mode 100644 exercises/19_smart_pointers/arc1.rs create mode 100644 exercises/19_smart_pointers/box1.rs create mode 100644 exercises/19_smart_pointers/cow1.rs create mode 100644 exercises/19_smart_pointers/rc1.rs create mode 100644 exercises/20_threads/README.md create mode 100644 exercises/20_threads/threads1.rs create mode 100644 exercises/20_threads/threads2.rs create mode 100644 exercises/20_threads/threads3.rs create mode 100644 exercises/21_macros/README.md create mode 100644 exercises/21_macros/macros1.rs create mode 100644 exercises/21_macros/macros2.rs create mode 100644 exercises/21_macros/macros3.rs create mode 100644 exercises/21_macros/macros4.rs create mode 100644 exercises/22_clippy/README.md create mode 100644 exercises/22_clippy/clippy1.rs create mode 100644 exercises/22_clippy/clippy2.rs create mode 100644 exercises/22_clippy/clippy3.rs create mode 100644 exercises/23_conversions/README.md create mode 100644 exercises/23_conversions/as_ref_mut.rs create mode 100644 exercises/23_conversions/from_into.rs create mode 100644 exercises/23_conversions/from_str.rs create mode 100644 exercises/23_conversions/try_from_into.rs create mode 100644 exercises/23_conversions/using_as.rs create mode 100644 exercises/README.md create mode 100644 exercises/quizzes/README.md create mode 100644 exercises/quizzes/quiz1.rs create mode 100644 exercises/quizzes/quiz2.rs create mode 100644 exercises/quizzes/quiz3.rs create mode 100644 solutions/00_intro/intro1.rs create mode 100644 solutions/00_intro/intro2.rs create mode 100644 solutions/01_variables/variables1.rs create mode 100644 solutions/01_variables/variables2.rs create mode 100644 solutions/01_variables/variables3.rs create mode 100644 solutions/01_variables/variables4.rs create mode 100644 solutions/01_variables/variables5.rs create mode 100644 solutions/01_variables/variables6.rs create mode 100644 solutions/02_functions/functions1.rs create mode 100644 solutions/02_functions/functions2.rs create mode 100644 solutions/02_functions/functions3.rs create mode 100644 solutions/02_functions/functions4.rs create mode 100644 solutions/02_functions/functions5.rs create mode 100644 solutions/03_if/if1.rs create mode 100644 solutions/03_if/if2.rs create mode 100644 solutions/03_if/if3.rs create mode 100644 solutions/04_primitive_types/primitive_types1.rs create mode 100644 solutions/04_primitive_types/primitive_types2.rs create mode 100644 solutions/04_primitive_types/primitive_types3.rs create mode 100644 solutions/04_primitive_types/primitive_types4.rs create mode 100644 solutions/04_primitive_types/primitive_types5.rs create mode 100644 solutions/04_primitive_types/primitive_types6.rs create mode 100644 solutions/05_vecs/vecs1.rs create mode 100644 solutions/05_vecs/vecs2.rs create mode 100644 solutions/06_move_semantics/move_semantics1.rs create mode 100644 solutions/06_move_semantics/move_semantics2.rs create mode 100644 solutions/06_move_semantics/move_semantics3.rs create mode 100644 solutions/06_move_semantics/move_semantics4.rs create mode 100644 solutions/06_move_semantics/move_semantics5.rs create mode 100644 solutions/07_structs/structs1.rs create mode 100644 solutions/07_structs/structs2.rs create mode 100644 solutions/07_structs/structs3.rs create mode 100644 solutions/08_enums/enums1.rs create mode 100644 solutions/08_enums/enums2.rs create mode 100644 solutions/08_enums/enums3.rs create mode 100644 solutions/09_strings/strings1.rs create mode 100644 solutions/09_strings/strings2.rs create mode 100644 solutions/09_strings/strings3.rs create mode 100644 solutions/09_strings/strings4.rs create mode 100644 solutions/10_modules/modules1.rs create mode 100644 solutions/10_modules/modules2.rs create mode 100644 solutions/10_modules/modules3.rs create mode 100644 solutions/11_hashmaps/hashmaps1.rs create mode 100644 solutions/11_hashmaps/hashmaps2.rs create mode 100644 solutions/11_hashmaps/hashmaps3.rs create mode 100644 solutions/12_options/options1.rs create mode 100644 solutions/12_options/options2.rs create mode 100644 solutions/12_options/options3.rs create mode 100644 solutions/13_error_handling/errors1.rs create mode 100644 solutions/13_error_handling/errors2.rs create mode 100644 solutions/13_error_handling/errors3.rs create mode 100644 solutions/13_error_handling/errors4.rs create mode 100644 solutions/13_error_handling/errors5.rs create mode 100644 solutions/13_error_handling/errors6.rs create mode 100644 solutions/14_generics/generics1.rs create mode 100644 solutions/14_generics/generics2.rs create mode 100644 solutions/15_traits/traits1.rs create mode 100644 solutions/15_traits/traits2.rs create mode 100644 solutions/15_traits/traits3.rs create mode 100644 solutions/15_traits/traits4.rs create mode 100644 solutions/15_traits/traits5.rs create mode 100644 solutions/16_lifetimes/lifetimes1.rs create mode 100644 solutions/16_lifetimes/lifetimes2.rs create mode 100644 solutions/16_lifetimes/lifetimes3.rs create mode 100644 solutions/17_tests/tests1.rs create mode 100644 solutions/17_tests/tests2.rs create mode 100644 solutions/17_tests/tests3.rs create mode 100644 solutions/18_iterators/iterators1.rs create mode 100644 solutions/18_iterators/iterators2.rs create mode 100644 solutions/18_iterators/iterators3.rs create mode 100644 solutions/18_iterators/iterators4.rs create mode 100644 solutions/18_iterators/iterators5.rs create mode 100644 solutions/19_smart_pointers/arc1.rs create mode 100644 solutions/19_smart_pointers/box1.rs create mode 100644 solutions/19_smart_pointers/cow1.rs create mode 100644 solutions/19_smart_pointers/rc1.rs create mode 100644 solutions/20_threads/threads1.rs create mode 100644 solutions/20_threads/threads2.rs create mode 100644 solutions/20_threads/threads3.rs create mode 100644 solutions/21_macros/macros1.rs create mode 100644 solutions/21_macros/macros2.rs create mode 100644 solutions/21_macros/macros3.rs create mode 100644 solutions/21_macros/macros4.rs create mode 100644 solutions/22_clippy/clippy1.rs create mode 100644 solutions/22_clippy/clippy2.rs create mode 100644 solutions/22_clippy/clippy3.rs create mode 100644 solutions/23_conversions/as_ref_mut.rs create mode 100644 solutions/23_conversions/from_into.rs create mode 100644 solutions/23_conversions/from_str.rs create mode 100644 solutions/23_conversions/try_from_into.rs create mode 100644 solutions/23_conversions/using_as.rs create mode 100644 solutions/README.md create mode 100644 solutions/quizzes/quiz1.rs create mode 100644 solutions/quizzes/quiz2.rs create mode 100644 solutions/quizzes/quiz3.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9182e2f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +Cargo.lock +target/ +.vscode/ diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..02a49d0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,218 @@ +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 = "2021" +# 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" + +[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" diff --git a/exercises/00_intro/README.md b/exercises/00_intro/README.md new file mode 100644 index 0000000..d32e4a8 --- /dev/null +++ b/exercises/00_intro/README.md @@ -0,0 +1,8 @@ +# Intro + +Rust uses the `print!` and `println!` macros to print text to the console. + +## Further information + +- [Hello World](https://doc.rust-lang.org/rust-by-example/hello.html) +- [Formatted print](https://doc.rust-lang.org/rust-by-example/hello/print.html) diff --git a/exercises/00_intro/intro1.rs b/exercises/00_intro/intro1.rs new file mode 100644 index 0000000..172a6ab --- /dev/null +++ b/exercises/00_intro/intro1.rs @@ -0,0 +1,24 @@ +// 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."); +} diff --git a/exercises/00_intro/intro2.rs b/exercises/00_intro/intro2.rs new file mode 100644 index 0000000..c6cb645 --- /dev/null +++ b/exercises/00_intro/intro2.rs @@ -0,0 +1,4 @@ +fn main() { + // TODO: Fix the code to print "Hello world!". + printline!("Hello world!"); +} diff --git a/exercises/01_variables/README.md b/exercises/01_variables/README.md new file mode 100644 index 0000000..7964ff2 --- /dev/null +++ b/exercises/01_variables/README.md @@ -0,0 +1,9 @@ +# Variables + +In Rust, variables are immutable by default. +When a variable is immutable, once a value is bound to a name, you can’t change that value. +You can make them mutable by adding `mut` in front of the variable name. + +## Further information + +- [Variables and Mutability](https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html) diff --git a/exercises/01_variables/variables1.rs b/exercises/01_variables/variables1.rs new file mode 100644 index 0000000..f83b44d --- /dev/null +++ b/exercises/01_variables/variables1.rs @@ -0,0 +1,6 @@ +fn main() { + // TODO: Add the missing keyword. + x = 5; + + println!("x has the value {x}"); +} diff --git a/exercises/01_variables/variables2.rs b/exercises/01_variables/variables2.rs new file mode 100644 index 0000000..e2a3603 --- /dev/null +++ b/exercises/01_variables/variables2.rs @@ -0,0 +1,10 @@ +fn main() { + // TODO: Change the line below to fix the compiler error. + let x; + + if x == 10 { + println!("x is ten!"); + } else { + println!("x is not ten!"); + } +} diff --git a/exercises/01_variables/variables3.rs b/exercises/01_variables/variables3.rs new file mode 100644 index 0000000..06f35bb --- /dev/null +++ b/exercises/01_variables/variables3.rs @@ -0,0 +1,6 @@ +fn main() { + // TODO: Change the line below to fix the compiler error. + let x: i32; + + println!("Number {x}"); +} diff --git a/exercises/01_variables/variables4.rs b/exercises/01_variables/variables4.rs new file mode 100644 index 0000000..6c138b1 --- /dev/null +++ b/exercises/01_variables/variables4.rs @@ -0,0 +1,8 @@ +// TODO: Fix the compiler error. +fn main() { + let x = 3; + println!("Number {x}"); + + x = 5; // Don't change this line + println!("Number {x}"); +} diff --git a/exercises/01_variables/variables5.rs b/exercises/01_variables/variables5.rs new file mode 100644 index 0000000..49db8e9 --- /dev/null +++ b/exercises/01_variables/variables5.rs @@ -0,0 +1,8 @@ +fn main() { + let number = "T-H-R-E-E"; // Don't change this line + println!("Spell a number: {}", number); + + // TODO: Fix the compiler error by changing the line below without renaming the variable. + number = 3; + println!("Number plus two is: {}", number + 2); +} diff --git a/exercises/01_variables/variables6.rs b/exercises/01_variables/variables6.rs new file mode 100644 index 0000000..4a040fd --- /dev/null +++ b/exercises/01_variables/variables6.rs @@ -0,0 +1,6 @@ +// TODO: Change the line below to fix the compiler error. +const NUMBER = 3; + +fn main() { + println!("Number: {NUMBER}"); +} diff --git a/exercises/02_functions/README.md b/exercises/02_functions/README.md new file mode 100644 index 0000000..6662d0d --- /dev/null +++ b/exercises/02_functions/README.md @@ -0,0 +1,8 @@ +# Functions + +Here, you'll learn how to write functions and how the Rust compiler can help you debug errors even +in more complex code. + +## Further information + +- [How Functions Work](https://doc.rust-lang.org/book/ch03-03-how-functions-work.html) diff --git a/exercises/02_functions/functions1.rs b/exercises/02_functions/functions1.rs new file mode 100644 index 0000000..a812c21 --- /dev/null +++ b/exercises/02_functions/functions1.rs @@ -0,0 +1,5 @@ +// TODO: Add some function with the name `call_me` without arguments or a return value. + +fn main() { + call_me(); // Don't change this line +} diff --git a/exercises/02_functions/functions2.rs b/exercises/02_functions/functions2.rs new file mode 100644 index 0000000..2c773c6 --- /dev/null +++ b/exercises/02_functions/functions2.rs @@ -0,0 +1,10 @@ +// TODO: Add the missing type of the argument `num` after the colon `:`. +fn call_me(num:) { + for i in 0..num { + println!("Ring! Call number {}", i + 1); + } +} + +fn main() { + call_me(3); +} diff --git a/exercises/02_functions/functions3.rs b/exercises/02_functions/functions3.rs new file mode 100644 index 0000000..8d65477 --- /dev/null +++ b/exercises/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() { + // TODO: Fix the function call. + call_me(); +} diff --git a/exercises/02_functions/functions4.rs b/exercises/02_functions/functions4.rs new file mode 100644 index 0000000..b22bffd --- /dev/null +++ b/exercises/02_functions/functions4.rs @@ -0,0 +1,22 @@ +// This store is having a sale where if the price is an even number, you get 10 +// Rustbucks off, but if it's an odd number, it's 3 Rustbucks off. +// Don't worry about the function bodies themselves, we are only interested in +// the signatures for now. + +fn is_even(num: i64) -> bool { + num % 2 == 0 +} + +// TODO: Fix the function signature. +fn sale_price(price: 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/exercises/02_functions/functions5.rs b/exercises/02_functions/functions5.rs new file mode 100644 index 0000000..34a2ac7 --- /dev/null +++ b/exercises/02_functions/functions5.rs @@ -0,0 +1,9 @@ +// TODO: Fix the function body without changing the signature. +fn square(num: i32) -> i32 { + num * num; +} + +fn main() { + let answer = square(3); + println!("The square of 3 is {answer}"); +} diff --git a/exercises/03_if/README.md b/exercises/03_if/README.md new file mode 100644 index 0000000..b52c392 --- /dev/null +++ b/exercises/03_if/README.md @@ -0,0 +1,7 @@ +# If + +`if`, the most basic (but still surprisingly versatile!) type of control flow, is what you'll learn here. + +## Further information + +- [Control Flow - if expressions](https://doc.rust-lang.org/book/ch03-05-control-flow.html#if-expressions) diff --git a/exercises/03_if/if1.rs b/exercises/03_if/if1.rs new file mode 100644 index 0000000..e5a3c5a --- /dev/null +++ b/exercises/03_if/if1.rs @@ -0,0 +1,32 @@ +fn bigger(a: i32, b: i32) -> i32 { + // TODO: Complete this function to return the bigger number! + // If both numbers are equal, any of them can be returned. + // Do not use: + // - another function call + // - additional variables +} + +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/exercises/03_if/if2.rs b/exercises/03_if/if2.rs new file mode 100644 index 0000000..593a77a --- /dev/null +++ b/exercises/03_if/if2.rs @@ -0,0 +1,35 @@ +// TODO: Fix the compiler error on this function. +fn foo_if_fizz(fizzish: &str) -> &str { + if fizzish == "fizz" { + "foo" + } else { + 1 + } +} + +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 foo_for_fizz() { + // This means that calling `foo_if_fizz` with the argument "fizz" should return "foo". + assert_eq!(foo_if_fizz("fizz"), "foo"); + } + + #[test] + fn bar_for_fuzz() { + assert_eq!(foo_if_fizz("fuzz"), "bar"); + } + + #[test] + fn default_to_baz() { + assert_eq!(foo_if_fizz("literally anything"), "baz"); + } +} diff --git a/exercises/03_if/if3.rs b/exercises/03_if/if3.rs new file mode 100644 index 0000000..89164eb --- /dev/null +++ b/exercises/03_if/if3.rs @@ -0,0 +1,53 @@ +fn animal_habitat(animal: &str) -> &str { + // TODO: Fix the compiler error in the statement below. + let identifier = if animal == "crab" { + 1 + } else if animal == "gopher" { + 2.0 + } else if animal == "snake" { + 3 + } else { + "Unknown" + }; + + // 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/exercises/04_primitive_types/README.md b/exercises/04_primitive_types/README.md new file mode 100644 index 0000000..d67668a --- /dev/null +++ b/exercises/04_primitive_types/README.md @@ -0,0 +1,9 @@ +# Primitive Types + +Rust has a couple of basic types that are directly implemented into the +compiler. In this section, we'll go through the most important ones. + +## Further information + +- [Data Types](https://doc.rust-lang.org/book/ch03-02-data-types.html) +- [The Slice Type](https://doc.rust-lang.org/book/ch04-03-slices.html) diff --git a/exercises/04_primitive_types/primitive_types1.rs b/exercises/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000..84923c7 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types1.rs @@ -0,0 +1,15 @@ +// Booleans (`bool`) + +fn main() { + let is_morning = true; + if is_morning { + println!("Good morning!"); + } + + // TODO: Define a boolean variable with the name `is_evening` before the `if` statement below. + // The value of the variable should be the negation (opposite) of `is_morning`. + // let … + if is_evening { + println!("Good evening!"); + } +} diff --git a/exercises/04_primitive_types/primitive_types2.rs b/exercises/04_primitive_types/primitive_types2.rs new file mode 100644 index 0000000..1401847 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types2.rs @@ -0,0 +1,28 @@ +// 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!"); + } + + // TODO: Analogous to the example before, declare a variable called `your_character` + // below with your favorite character. + // Try a letter, try a digit (in single quotes), try a special character, try a character + // from a different language than your own, try an emoji 😉 + // let your_character = ''; + + if your_character.is_alphabetic() { + println!("Alphabetical!"); + } else if your_character.is_numeric() { + println!("Numerical!"); + } else { + println!("Neither alphabetic nor numeric!"); + } +} diff --git a/exercises/04_primitive_types/primitive_types3.rs b/exercises/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000..9b79c0c --- /dev/null +++ b/exercises/04_primitive_types/primitive_types3.rs @@ -0,0 +1,11 @@ +fn main() { + // TODO: Create an array called `a` with at least 100 elements in it. + // let a = ??? + + if a.len() >= 100 { + println!("Wow, that's a big array!"); + } else { + println!("Meh, I eat arrays like that for breakfast."); + panic!("Array not big enough, more elements needed"); + } +} diff --git a/exercises/04_primitive_types/primitive_types4.rs b/exercises/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000..16e4fd9 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types4.rs @@ -0,0 +1,16 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn slice_out_of_array() { + let a = [1, 2, 3, 4, 5]; + + // TODO: Get a slice called `nice_slice` out of the array `a` so that the test passes. + // let nice_slice = ??? + + assert_eq!([2, 3, 4], nice_slice); + } +} diff --git a/exercises/04_primitive_types/primitive_types5.rs b/exercises/04_primitive_types/primitive_types5.rs new file mode 100644 index 0000000..6e00ef5 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types5.rs @@ -0,0 +1,8 @@ +fn main() { + let cat = ("Furry McFurson", 3.5); + + // TODO: Destructure the `cat` tuple in one statement so that the println works. + // let /* your pattern here */ = cat; + + println!("{name} is {age} years old"); +} diff --git a/exercises/04_primitive_types/primitive_types6.rs b/exercises/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000..a97e531 --- /dev/null +++ b/exercises/04_primitive_types/primitive_types6.rs @@ -0,0 +1,17 @@ +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + #[test] + fn indexing_tuple() { + let numbers = (1, 2, 3); + + // TODO: Use a tuple index to access the second element of `numbers` + // and assign it to a variable called `second`. + // let second = ???; + + assert_eq!(second, 2, "This is not the 2nd number in the tuple!"); + } +} diff --git a/exercises/05_vecs/README.md b/exercises/05_vecs/README.md new file mode 100644 index 0000000..e1b6128 --- /dev/null +++ b/exercises/05_vecs/README.md @@ -0,0 +1,17 @@ +# Vectors + +Vectors are one of the most-used Rust data structures. In other programming +languages, they'd simply be called Arrays, but since Rust operates on a +bit of a lower level, an array in Rust is stored on the stack (meaning it +can't grow or shrink, and the size needs to be known at compile time), +and a Vector is stored in the heap (where these restrictions do not apply). + +Vectors are a bit of a later chapter in the book, but we think that they're +useful enough to talk about them a bit earlier. We shall be talking about +the other useful data structure, hash maps, later. + +## Further information + +- [Storing Lists of Values with Vectors](https://doc.rust-lang.org/book/ch08-01-vectors.html) +- [`iter_mut`](https://doc.rust-lang.org/std/primitive.slice.html#method.iter_mut) +- [`map`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map) diff --git a/exercises/05_vecs/vecs1.rs b/exercises/05_vecs/vecs1.rs new file mode 100644 index 0000000..68e1aff --- /dev/null +++ b/exercises/05_vecs/vecs1.rs @@ -0,0 +1,24 @@ +fn array_and_vec() -> ([i32; 4], Vec) { + let a = [10, 20, 30, 40]; // Array + + // TODO: Create a vector called `v` which contains the exact same elements as in the array `a`. + // Use the vector macro. + // let v = ???; + + (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/exercises/05_vecs/vecs2.rs b/exercises/05_vecs/vecs2.rs new file mode 100644 index 0000000..a9be258 --- /dev/null +++ b/exercises/05_vecs/vecs2.rs @@ -0,0 +1,60 @@ +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 +} + +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| { + // ??? + }) + .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/exercises/06_move_semantics/README.md b/exercises/06_move_semantics/README.md new file mode 100644 index 0000000..54ddd8e --- /dev/null +++ b/exercises/06_move_semantics/README.md @@ -0,0 +1,10 @@ +# Move Semantics + +These exercises are adapted from [pnkfelix](https://github.com/pnkfelix)'s [Rust Tutorial](https://pnkfelix.github.io/rust-examples-icfp2014/) -- Thank you Felix!!! + +## Further information + +For this section, the book links are especially important. + +- [Ownership](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html) +- [Reference and borrowing](https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html) diff --git a/exercises/06_move_semantics/move_semantics1.rs b/exercises/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000..4eb3d61 --- /dev/null +++ b/exercises/06_move_semantics/move_semantics1.rs @@ -0,0 +1,24 @@ +// TODO: Fix the compiler error in this function. +fn fill_vec(vec: Vec) -> Vec { + let 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/exercises/06_move_semantics/move_semantics2.rs b/exercises/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000..a3ab7a0 --- /dev/null +++ b/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); + + assert_eq!(vec0, [22, 44, 66]); + assert_eq!(vec1, [22, 44, 66, 88]); + } +} diff --git a/exercises/06_move_semantics/move_semantics3.rs b/exercises/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000..11dbbbe --- /dev/null +++ b/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(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/exercises/06_move_semantics/move_semantics4.rs b/exercises/06_move_semantics/move_semantics4.rs new file mode 100644 index 0000000..56da988 --- /dev/null +++ b/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; + let z = &mut x; + y.push(42); + z.push(13); + assert_eq!(x, [42, 13]); + } +} diff --git a/exercises/06_move_semantics/move_semantics5.rs b/exercises/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000..cd0dafd --- /dev/null +++ b/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/exercises/07_structs/README.md b/exercises/07_structs/README.md new file mode 100644 index 0000000..3fc1fdc --- /dev/null +++ b/exercises/07_structs/README.md @@ -0,0 +1,8 @@ +# Structs + +Rust has three struct types: a classic C struct, a tuple struct, and a unit struct. + +## Further information + +- [Structures](https://doc.rust-lang.org/book/ch05-01-defining-structs.html) +- [Method Syntax](https://doc.rust-lang.org/book/ch05-03-method-syntax.html) diff --git a/exercises/07_structs/structs1.rs b/exercises/07_structs/structs1.rs new file mode 100644 index 0000000..959c4c6 --- /dev/null +++ b/exercises/07_structs/structs1.rs @@ -0,0 +1,47 @@ +struct ColorRegularStruct { + // TODO: Add the fields that the test `regular_structs` expects. + // What types should the fields have? What are the minimum and maximum values for RGB colors? +} + +struct ColorTupleStruct(/* TODO: Add the fields that the test `tuple_structs` expects */); + +#[derive(Debug)] +struct UnitStruct; + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn regular_structs() { + // TODO: Instantiate a regular struct. + // let green = + + assert_eq!(green.red, 0); + assert_eq!(green.green, 255); + assert_eq!(green.blue, 0); + } + + #[test] + fn tuple_structs() { + // TODO: Instantiate a tuple struct. + // let green = + + assert_eq!(green.0, 0); + assert_eq!(green.1, 255); + assert_eq!(green.2, 0); + } + + #[test] + fn unit_structs() { + // TODO: Instantiate a unit struct. + // let unit_struct = + let message = format!("{unit_struct:?}s are fun!"); + + assert_eq!(message, "UnitStructs are fun!"); + } +} diff --git a/exercises/07_structs/structs2.rs b/exercises/07_structs/structs2.rs new file mode 100644 index 0000000..79141af --- /dev/null +++ b/exercises/07_structs/structs2.rs @@ -0,0 +1,47 @@ +#[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(); + + // TODO: Create your own order using the update syntax and template above! + // let your_order = + + assert_eq!(your_order.name, "Hacker in Rust"); + assert_eq!(your_order.year, order_template.year); + assert_eq!(your_order.made_by_phone, order_template.made_by_phone); + assert_eq!(your_order.made_by_mobile, order_template.made_by_mobile); + assert_eq!(your_order.made_by_email, order_template.made_by_email); + assert_eq!(your_order.item_number, order_template.item_number); + assert_eq!(your_order.count, 1); + } +} diff --git a/exercises/07_structs/structs3.rs b/exercises/07_structs/structs3.rs new file mode 100644 index 0000000..69e5ced --- /dev/null +++ b/exercises/07_structs/structs3.rs @@ -0,0 +1,87 @@ +// 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, + } + } + + // TODO: Add the correct return type to the function signature. + fn is_international(&self) { + // TODO: Read the tests that use this method to find out when a package + // is considered international. + } + + // TODO: Add the correct return type to the function signature. + fn get_fees(&self, cents_per_gram: u32) { + // TODO: Calculate the package's fees. + } +} + +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/exercises/08_enums/README.md b/exercises/08_enums/README.md new file mode 100644 index 0000000..30d4d91 --- /dev/null +++ b/exercises/08_enums/README.md @@ -0,0 +1,10 @@ +# Enums + +Rust allows you to define types called "enums" which enumerate possible values. +Enums are a feature in many languages, but their capabilities differ in each language. Rust’s enums are most similar to algebraic data types in functional languages, such as F#, OCaml, and Haskell. +Useful in combination with enums is Rust's "pattern matching" facility, which makes it easy to run different code for different values of an enumeration. + +## Further information + +- [Enums](https://doc.rust-lang.org/book/ch06-00-enums.html) +- [Pattern syntax](https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html) diff --git a/exercises/08_enums/enums1.rs b/exercises/08_enums/enums1.rs new file mode 100644 index 0000000..c0d0c30 --- /dev/null +++ b/exercises/08_enums/enums1.rs @@ -0,0 +1,12 @@ +#[derive(Debug)] +enum Message { + // TODO: Define a few types of messages as used below. +} + +fn main() { + println!("{:?}", Message::Resize); + println!("{:?}", Message::Move); + println!("{:?}", Message::Echo); + println!("{:?}", Message::ChangeColor); + println!("{:?}", Message::Quit); +} diff --git a/exercises/08_enums/enums2.rs b/exercises/08_enums/enums2.rs new file mode 100644 index 0000000..29ed1b6 --- /dev/null +++ b/exercises/08_enums/enums2.rs @@ -0,0 +1,35 @@ +#![allow(dead_code)] + +#[derive(Debug)] +struct Point { + x: u64, + y: u64, +} + +#[derive(Debug)] +enum Message { + // TODO: Define the different variants used below. +} + +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/exercises/08_enums/enums3.rs b/exercises/08_enums/enums3.rs new file mode 100644 index 0000000..66c4675 --- /dev/null +++ b/exercises/08_enums/enums3.rs @@ -0,0 +1,84 @@ +struct Point { + x: u64, + y: u64, +} + +enum Message { + // TODO: Implement the message variant types based on their usage below. +} + +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) { + // TODO: Create a match expression to process the different message + // variants using the methods defined above. + } +} + +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/exercises/09_strings/README.md b/exercises/09_strings/README.md new file mode 100644 index 0000000..fa2104c --- /dev/null +++ b/exercises/09_strings/README.md @@ -0,0 +1,9 @@ +# Strings + +Rust has two string types, a string slice (`&str`) and an owned string (`String`). +We're not going to dictate when you should use which one, but we'll show you how +to identify and create them, as well as use them. + +## Further information + +- [Strings](https://doc.rust-lang.org/book/ch08-02-strings.html) diff --git a/exercises/09_strings/strings1.rs b/exercises/09_strings/strings1.rs new file mode 100644 index 0000000..6abdbb4 --- /dev/null +++ b/exercises/09_strings/strings1.rs @@ -0,0 +1,9 @@ +// TODO: Fix the compiler error without changing the function signature. +fn current_favorite_color() -> String { + "blue" +} + +fn main() { + let answer = current_favorite_color(); + println!("My current favorite color is {answer}"); +} diff --git a/exercises/09_strings/strings2.rs b/exercises/09_strings/strings2.rs new file mode 100644 index 0000000..93d9cb6 --- /dev/null +++ b/exercises/09_strings/strings2.rs @@ -0,0 +1,14 @@ +// TODO: Fix the compiler error in the `main` function without changing this function. +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/exercises/09_strings/strings3.rs b/exercises/09_strings/strings3.rs new file mode 100644 index 0000000..39fce18 --- /dev/null +++ b/exercises/09_strings/strings3.rs @@ -0,0 +1,45 @@ +fn trim_me(input: &str) -> &str { + // TODO: Remove whitespace from both ends of a string. +} + +fn compose_me(input: &str) -> String { + // TODO: Add " world!" to the string! There are multiple ways to do this. +} + +fn replace_me(input: &str) -> String { + // TODO: Replace "cars" in the string with "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!"); + } + + #[test] + fn compose_a_string() { + assert_eq!(compose_me("Hello"), "Hello world!"); + assert_eq!(compose_me("Goodbye"), "Goodbye world!"); + } + + #[test] + fn replace_a_string() { + assert_eq!( + replace_me("I think cars are cool"), + "I think balloons are cool", + ); + assert_eq!( + replace_me("I love to look at cars"), + "I love to look at balloons", + ); + } +} diff --git a/exercises/09_strings/strings4.rs b/exercises/09_strings/strings4.rs new file mode 100644 index 0000000..4730726 --- /dev/null +++ b/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() { + placeholder("blue"); + + placeholder("red".to_string()); + + placeholder(String::from("hi")); + + placeholder("rust is fun!".to_owned()); + + placeholder("nice weather".into()); + + placeholder(format!("Interpolation {}", "Station")); + + // WARNING: This is byte indexing, not character indexing. + // Character indexing can be done using `s.chars().nth(INDEX)`. + placeholder(&String::from("abc")[0..1]); + + placeholder(" hello there ".trim()); + + placeholder("Happy Monday!".replace("Mon", "Tues")); + + placeholder("mY sHiFt KeY iS sTiCkY".to_lowercase()); +} diff --git a/exercises/10_modules/README.md b/exercises/10_modules/README.md new file mode 100644 index 0000000..3dc8a48 --- /dev/null +++ b/exercises/10_modules/README.md @@ -0,0 +1,7 @@ +# Modules + +In this section we'll give you an introduction to Rust's module system. + +## Further information + +- [The Module System](https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) diff --git a/exercises/10_modules/modules1.rs b/exercises/10_modules/modules1.rs new file mode 100644 index 0000000..d97ab23 --- /dev/null +++ b/exercises/10_modules/modules1.rs @@ -0,0 +1,16 @@ +// TODO: Fix the compiler error about calling a private function. +mod sausage_factory { + // Don't let anybody outside of this module see this! + fn get_secret_recipe() -> String { + String::from("Ginger") + } + + fn make_sausage() { + get_secret_recipe(); + println!("sausage!"); + } +} + +fn main() { + sausage_factory::make_sausage(); +} diff --git a/exercises/10_modules/modules2.rs b/exercises/10_modules/modules2.rs new file mode 100644 index 0000000..02eb80a --- /dev/null +++ b/exercises/10_modules/modules2.rs @@ -0,0 +1,27 @@ +// You can bring module paths into scopes and provide new names for them with +// the `use` and `as` keywords. + +#[allow(dead_code)] +mod delicious_snacks { + // TODO: Add the following two `use` statements after fixing them. + // use self::fruits::PEAR as ???; + // use self::veggies::CUCUMBER as ???; + + 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/exercises/10_modules/modules3.rs b/exercises/10_modules/modules3.rs new file mode 100644 index 0000000..691608d --- /dev/null +++ b/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 ???; + +fn main() { + match SystemTime::now().duration_since(UNIX_EPOCH) { + Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()), + Err(_) => panic!("SystemTime before UNIX EPOCH!"), + } +} diff --git a/exercises/11_hashmaps/README.md b/exercises/11_hashmaps/README.md new file mode 100644 index 0000000..80ec144 --- /dev/null +++ b/exercises/11_hashmaps/README.md @@ -0,0 +1,12 @@ +# Hashmaps + +A *hash map* allows you to associate a value with a particular key. +You may also know this by the names [*unordered map* in C++](https://en.cppreference.com/w/cpp/container/unordered_map), +[*dictionary* in Python](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) or an *associative array* in other languages. + +This is the other data structure that we've been talking about before, when +talking about Vecs. + +## Further information + +- [Storing Keys with Associated Values in Hash Maps](https://doc.rust-lang.org/book/ch08-03-hash-maps.html) diff --git a/exercises/11_hashmaps/hashmaps1.rs b/exercises/11_hashmaps/hashmaps1.rs new file mode 100644 index 0000000..74001d0 --- /dev/null +++ b/exercises/11_hashmaps/hashmaps1.rs @@ -0,0 +1,40 @@ +// 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 = + + // Two bananas are already given for you :) + basket.insert(String::from("banana"), 2); + + // TODO: Put more fruits in your basket. + + 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/exercises/11_hashmaps/hashmaps2.rs b/exercises/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000..e9f53fe --- /dev/null +++ b/exercises/11_hashmaps/hashmaps2.rs @@ -0,0 +1,97 @@ +// 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 { + // TODO: Insert new fruits if they are not already present in the + // basket. Note that you are not allowed to put any type of fruit that's + // already present! + } +} + +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/exercises/11_hashmaps/hashmaps3.rs b/exercises/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000..7e9584d --- /dev/null +++ b/exercises/11_hashmaps/hashmaps3.rs @@ -0,0 +1,77 @@ +// 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::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. + } + + 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/exercises/12_options/README.md b/exercises/12_options/README.md new file mode 100644 index 0000000..624572a --- /dev/null +++ b/exercises/12_options/README.md @@ -0,0 +1,21 @@ +# Options + +Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. +Option types are very common in Rust code, as they have a number of uses: + +- Initial values +- Return values for functions that are not defined over their entire input range (partial functions) +- Return value for otherwise reporting simple errors, where None is returned on error +- Optional struct fields +- Struct fields that can be loaned or "taken" +- Optional function arguments +- Nullable pointers +- Swapping things out of difficult situations + +## Further Information + +- [Option Enum Format](https://doc.rust-lang.org/book/ch10-01-syntax.html#in-enum-definitions) +- [Option Module Documentation](https://doc.rust-lang.org/std/option/) +- [Option Enum Documentation](https://doc.rust-lang.org/std/option/enum.Option.html) +- [if let](https://doc.rust-lang.org/rust-by-example/flow_control/if_let.html) +- [while let](https://doc.rust-lang.org/rust-by-example/flow_control/while_let.html) diff --git a/exercises/12_options/options1.rs b/exercises/12_options/options1.rs new file mode 100644 index 0000000..9964807 --- /dev/null +++ b/exercises/12_options/options1.rs @@ -0,0 +1,36 @@ +// 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 { + // TODO: Complete the function body. +} + +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 icecreams = maybe_icecream(12); + + assert_eq!(icecreams, 5); // Don't change this line. + } + + #[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/exercises/12_options/options2.rs b/exercises/12_options/options2.rs new file mode 100644 index 0000000..07c27c6 --- /dev/null +++ b/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`. + 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. + integer = optional_integers.pop() { + assert_eq!(integer, cursor); + cursor -= 1; + } + + assert_eq!(cursor, 0); + } +} diff --git a/exercises/12_options/options3.rs b/exercises/12_options/options3.rs new file mode 100644 index 0000000..4cedb51 --- /dev/null +++ b/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(p) => println!("Co-ordinates are {},{}", p.x, p.y), + _ => panic!("No match!"), + } + + println!("{optional_point:?}"); // Don't change this line. +} diff --git a/exercises/13_error_handling/README.md b/exercises/13_error_handling/README.md new file mode 100644 index 0000000..3b21f2b --- /dev/null +++ b/exercises/13_error_handling/README.md @@ -0,0 +1,12 @@ +# Error handling + +Most errors aren’t serious enough to require the program to stop entirely. +Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. +For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process. + +## Further information + +- [Error Handling](https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html) +- [Generics](https://doc.rust-lang.org/book/ch10-01-syntax.html) +- [Result](https://doc.rust-lang.org/rust-by-example/error/result.html) +- [Boxing errors](https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/boxing_errors.html) diff --git a/exercises/13_error_handling/errors1.rs b/exercises/13_error_handling/errors1.rs new file mode 100644 index 0000000..e07fddc --- /dev/null +++ b/exercises/13_error_handling/errors1.rs @@ -0,0 +1,41 @@ +// 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) -> Option { + if name.is_empty() { + // Empty names aren't allowed + None + } else { + Some(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/exercises/13_error_handling/errors2.rs b/exercises/13_error_handling/errors2.rs new file mode 100644 index 0000000..defe359 --- /dev/null +++ b/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/exercises/13_error_handling/errors3.rs b/exercises/13_error_handling/errors3.rs new file mode 100644 index 0000000..8e8c38a --- /dev/null +++ b/exercises/13_error_handling/errors3.rs @@ -0,0 +1,31 @@ +// 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() { + 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."); + } +} diff --git a/exercises/13_error_handling/errors4.rs b/exercises/13_error_handling/errors4.rs new file mode 100644 index 0000000..ba01e54 --- /dev/null +++ b/exercises/13_error_handling/errors4.rs @@ -0,0 +1,37 @@ +#[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`. + 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/exercises/13_error_handling/errors5.rs b/exercises/13_error_handling/errors5.rs new file mode 100644 index 0000000..5721835 --- /dev/null +++ b/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() { + let pretend_user_input = "42"; + let x: i64 = pretend_user_input.parse()?; + println!("output={:?}", PositiveNonzeroInteger::new(x)?); + Ok(()) +} diff --git a/exercises/13_error_handling/errors6.rs b/exercises/13_error_handling/errors6.rs new file mode 100644 index 0000000..b1995e0 --- /dev/null +++ b/exercises/13_error_handling/errors6.rs @@ -0,0 +1,89 @@ +// 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(???) -> Self { ??? } +} + +#[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().unwrap(); + 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/exercises/14_generics/README.md b/exercises/14_generics/README.md new file mode 100644 index 0000000..0c8c8cb --- /dev/null +++ b/exercises/14_generics/README.md @@ -0,0 +1,11 @@ +# Generics + +Generics is the topic of generalizing types and functionalities to broader cases. +This is extremely useful for reducing code duplication in many ways, but can call for 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/exercises/14_generics/generics1.rs b/exercises/14_generics/generics1.rs new file mode 100644 index 0000000..87ed990 --- /dev/null +++ b/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::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/exercises/14_generics/generics2.rs b/exercises/14_generics/generics2.rs new file mode 100644 index 0000000..8908725 --- /dev/null +++ b/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: u32, +} + +// TODO: Adapt the struct's implementation to be generic over the wrapped value. +impl Wrapper { + fn new(value: u32) -> 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/exercises/15_traits/README.md b/exercises/15_traits/README.md new file mode 100644 index 0000000..ac87c64 --- /dev/null +++ b/exercises/15_traits/README.md @@ -0,0 +1,19 @@ +# Traits + +A trait is a collection of methods. + +Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the `String` data type implements the `From<&str>` trait. This allows a user to write `String::from("hello")`. + +In this way, traits are somewhat similar to Java interfaces and C++ abstract classes. + +Some additional common Rust traits include: + +- `Clone` (the `clone` method) +- `Display` (which allows formatted display via `{}`) +- `Debug` (which allows formatted display via `{:?}`) + +Because traits indicate shared behavior between data types, they are useful when writing generics. + +## Further information + +- [Traits](https://doc.rust-lang.org/book/ch10-02-traits.html) diff --git a/exercises/15_traits/traits1.rs b/exercises/15_traits/traits1.rs new file mode 100644 index 0000000..85be17e --- /dev/null +++ b/exercises/15_traits/traits1.rs @@ -0,0 +1,30 @@ +// 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 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/exercises/15_traits/traits2.rs b/exercises/15_traits/traits2.rs new file mode 100644 index 0000000..d724dc2 --- /dev/null +++ b/exercises/15_traits/traits2.rs @@ -0,0 +1,22 @@ +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. + +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/exercises/15_traits/traits3.rs b/exercises/15_traits/traits3.rs new file mode 100644 index 0000000..2e8969e --- /dev/null +++ b/exercises/15_traits/traits3.rs @@ -0,0 +1,40 @@ +#![allow(dead_code)] + +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; +} + +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/exercises/15_traits/traits4.rs b/exercises/15_traits/traits4.rs new file mode 100644 index 0000000..80092a6 --- /dev/null +++ b/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: ???, software2: ???) -> 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/exercises/15_traits/traits5.rs b/exercises/15_traits/traits5.rs new file mode 100644 index 0000000..5b356ac --- /dev/null +++ b/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: ???) -> 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/exercises/16_lifetimes/README.md b/exercises/16_lifetimes/README.md new file mode 100644 index 0000000..91373f7 --- /dev/null +++ b/exercises/16_lifetimes/README.md @@ -0,0 +1,22 @@ +# Lifetimes + +Lifetimes tell the compiler how to check whether references live long +enough to be valid in any given situation. For example lifetimes say +"make sure parameter 'a' lives as long as parameter 'b' so that the return +value is valid". + +They are only necessary on borrows, i.e. references, +since copied parameters or moves are owned in their scope and cannot +be referenced outside. Lifetimes mean that calling code of e.g. functions +can be checked to make sure their arguments are valid. Lifetimes are +restrictive of their callers. + +If you'd like to learn more about lifetime annotations, the +[lifetimekata](https://tfpk.github.io/lifetimekata/) project +has a similar style of exercises to Rustlings, but is all about +learning to write lifetime annotations. + +## Further information + +- [Lifetimes (in Rust By Example)](https://doc.rust-lang.org/stable/rust-by-example/scope/lifetime.html) +- [Validating References with Lifetimes](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html) diff --git a/exercises/16_lifetimes/lifetimes1.rs b/exercises/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000..19e2d39 --- /dev/null +++ b/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(x: &str, y: &str) -> &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/exercises/16_lifetimes/lifetimes2.rs b/exercises/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000..de5a5df --- /dev/null +++ b/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 result; + { + let string2 = String::from("xyz"); + result = longest(&string1, &string2); + } + println!("The longest string is '{result}'"); +} diff --git a/exercises/16_lifetimes/lifetimes3.rs b/exercises/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000..1cc2759 --- /dev/null +++ b/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 { + author: &str, + title: &str, +} + +fn main() { + let book = Book { + author: "George Orwell", + title: "1984", + }; + + println!("{} by {}", book.title, book.author); +} diff --git a/exercises/17_tests/README.md b/exercises/17_tests/README.md new file mode 100644 index 0000000..27c6818 --- /dev/null +++ b/exercises/17_tests/README.md @@ -0,0 +1,7 @@ +# Tests + +Going out of order from the book to cover tests -- many of the following exercises will ask you to make tests pass! + +## Further information + +- [Writing Tests](https://doc.rust-lang.org/book/ch11-01-writing-tests.html) diff --git a/exercises/17_tests/tests1.rs b/exercises/17_tests/tests1.rs new file mode 100644 index 0000000..7529f9f --- /dev/null +++ b/exercises/17_tests/tests1.rs @@ -0,0 +1,23 @@ +// 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. + + #[test] + fn you_can_assert() { + // TODO: Test the function `is_even` with some values. + assert!(); + assert!(); + } +} diff --git a/exercises/17_tests/tests2.rs b/exercises/17_tests/tests2.rs new file mode 100644 index 0000000..0c6573e --- /dev/null +++ b/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!(); + assert_eq!(); + assert_eq!(); + assert_eq!(); + } +} diff --git a/exercises/17_tests/tests3.rs b/exercises/17_tests/tests3.rs new file mode 100644 index 0000000..822184e --- /dev/null +++ b/exercises/17_tests/tests3.rs @@ -0,0 +1,49 @@ +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!(todo!(), 10); // Check width + assert_eq!(todo!(), 20); // Check height + } + + // TODO: This test should check if the program panics when we try to create + // a rectangle with negative width. + #[test] + 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] + fn negative_height() { + let _rect = Rectangle::new(10, -10); + } +} diff --git a/exercises/18_iterators/README.md b/exercises/18_iterators/README.md new file mode 100644 index 0000000..0e8b671 --- /dev/null +++ b/exercises/18_iterators/README.md @@ -0,0 +1,8 @@ +# Iterators + +This section will teach you about Iterators. + +## Further information + +- [Iterator](https://doc.rust-lang.org/book/ch13-02-iterators.html) +- [Iterator documentation](https://doc.rust-lang.org/stable/std/iter/) diff --git a/exercises/18_iterators/iterators1.rs b/exercises/18_iterators/iterators1.rs new file mode 100644 index 0000000..ca937ed --- /dev/null +++ b/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 = todo!(); + + assert_eq!(fav_fruits_iterator.next(), Some(&"banana")); + assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"avocado")); + assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + assert_eq!(fav_fruits_iterator.next(), Some(&"raspberry")); + assert_eq!(fav_fruits_iterator.next(), todo!()); // TODO: Replace `todo!()` + } +} diff --git a/exercises/18_iterators/iterators2.rs b/exercises/18_iterators/iterators2.rs new file mode 100644 index 0000000..5903e65 --- /dev/null +++ b/exercises/18_iterators/iterators2.rs @@ -0,0 +1,57 @@ +// 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) => todo!(), + } +} + +// 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 { + // ??? +} + +// 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 { + // ??? +} + +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/exercises/18_iterators/iterators3.rs b/exercises/18_iterators/iterators3.rs new file mode 100644 index 0000000..6b1eca1 --- /dev/null +++ b/exercises/18_iterators/iterators3.rs @@ -0,0 +1,73 @@ +#[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 { + todo!(); +} + +// TODO: Add the correct return type and complete the function body. +// Desired output: `Ok([1, 11, 1426, 3])` +fn result_with_list() { + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); +} + +// 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() { + let numbers = [27, 297, 38502, 81]; + let division_results = numbers.into_iter().map(|n| divide(n, 27)); +} + +fn main() { + // You can optionally experiment here. +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_success() { + assert_eq!(divide(81, 9), Ok(9)); + } + + #[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/exercises/18_iterators/iterators4.rs b/exercises/18_iterators/iterators4.rs new file mode 100644 index 0000000..c296f0e --- /dev/null +++ b/exercises/18_iterators/iterators4.rs @@ -0,0 +1,41 @@ +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 +} + +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/exercises/18_iterators/iterators5.rs b/exercises/18_iterators/iterators5.rs new file mode 100644 index 0000000..7e434cc --- /dev/null +++ b/exercises/18_iterators/iterators5.rs @@ -0,0 +1,153 @@ +// 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` 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` 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/exercises/19_smart_pointers/README.md b/exercises/19_smart_pointers/README.md new file mode 100644 index 0000000..d56d2b6 --- /dev/null +++ b/exercises/19_smart_pointers/README.md @@ -0,0 +1,12 @@ +# Smart Pointers + +In Rust, smart pointers are variables that contain an address in memory and reference some other data, but they also have additional metadata and capabilities. +Smart pointers in Rust often own the data they point to, while references only borrow data. + +## Further Information + +- [Smart Pointers](https://doc.rust-lang.org/book/ch15-00-smart-pointers.html) +- [Using Box to Point to Data on the Heap](https://doc.rust-lang.org/book/ch15-01-box.html) +- [Rc\, the Reference Counted Smart Pointer](https://doc.rust-lang.org/book/ch15-04-rc.html) +- [Shared-State Concurrency](https://doc.rust-lang.org/book/ch16-03-shared-state.html) +- [Cow Documentation](https://doc.rust-lang.org/std/borrow/enum.Cow.html) diff --git a/exercises/19_smart_pointers/arc1.rs b/exercises/19_smart_pointers/arc1.rs new file mode 100644 index 0000000..6bb860f --- /dev/null +++ b/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 = ???; + + let mut join_handles = Vec::new(); + + for offset in 0..8 { + // TODO: Define `child_numbers` using `shared_numbers`. + // let child_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/exercises/19_smart_pointers/box1.rs b/exercises/19_smart_pointers/box1.rs new file mode 100644 index 0000000..d70e1c3 --- /dev/null +++ b/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, List), + Nil, +} + +// TODO: Create an empty cons list. +fn create_empty_list() -> List { + todo!() +} + +// TODO: Create a non-empty cons list. +fn create_non_empty_list() -> List { + todo!() +} + +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/exercises/19_smart_pointers/cow1.rs b/exercises/19_smart_pointers/cow1.rs new file mode 100644 index 0000000..1566500 --- /dev/null +++ b/exercises/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); + // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. + assert!(matches!(input, todo!())); + } + + #[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); + // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. + assert!(matches!(input, todo!())); + } + + #[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); + // TODO: Replace `todo!()` with `Cow::Owned(_)` or `Cow::Borrowed(_)`. + assert!(matches!(input, todo!())); + } +} diff --git a/exercises/19_smart_pointers/rc1.rs b/exercises/19_smart_pointers/rc1.rs new file mode 100644 index 0000000..48e19dc --- /dev/null +++ b/exercises/19_smart_pointers/rc1.rs @@ -0,0 +1,106 @@ +// 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; + +#[allow(dead_code)] +#[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::new(Sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + saturn.details(); + + // TODO + let uranus = Planet::Uranus(Rc::new(Sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + uranus.details(); + + // TODO + let neptune = Planet::Neptune(Rc::new(Sun)); + println!("reference count = {}", Rc::strong_count(&sun)); // 9 references + neptune.details(); + + assert_eq!(Rc::strong_count(&sun), 9); + + drop(neptune); + println!("reference count = {}", Rc::strong_count(&sun)); // 8 references + + drop(uranus); + println!("reference count = {}", Rc::strong_count(&sun)); // 7 references + + drop(saturn); + println!("reference count = {}", Rc::strong_count(&sun)); // 6 references + + drop(jupiter); + println!("reference count = {}", Rc::strong_count(&sun)); // 5 references + + drop(mars); + println!("reference count = {}", Rc::strong_count(&sun)); // 4 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 3 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 2 references + + // TODO + println!("reference count = {}", Rc::strong_count(&sun)); // 1 reference + + assert_eq!(Rc::strong_count(&sun), 1); + } +} diff --git a/exercises/20_threads/README.md b/exercises/20_threads/README.md new file mode 100644 index 0000000..0b32fb1 --- /dev/null +++ b/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/exercises/20_threads/threads1.rs b/exercises/20_threads/threads1.rs new file mode 100644 index 0000000..01f9ff4 --- /dev/null +++ b/exercises/20_threads/threads1.rs @@ -0,0 +1,37 @@ +// This program spawns multiple threads that each run for at least 250ms, and +// each thread returns how much time they took to complete. The program should +// wait until all the spawned threads have finished and should collect their +// return values into a vector. + +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/exercises/20_threads/threads2.rs b/exercises/20_threads/threads2.rs new file mode 100644 index 0000000..7020cb9 --- /dev/null +++ b/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/exercises/20_threads/threads3.rs b/exercises/20_threads/threads3.rs new file mode 100644 index 0000000..6d16bd9 --- /dev/null +++ b/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/exercises/21_macros/README.md b/exercises/21_macros/README.md new file mode 100644 index 0000000..337816d --- /dev/null +++ b/exercises/21_macros/README.md @@ -0,0 +1,14 @@ +# Macros + +Rust's macro system is very powerful, but also kind of difficult to wrap your +head around. We're not going to teach you how to write your own fully-featured +macros. Instead, we'll show you how to use and create them. + +If you'd like to learn more about writing your own macros, the +[macrokata](https://github.com/tfpk/macrokata) project has a similar style +of exercises to Rustlings, but is all about learning to write Macros. + +## Further information + +- [Macros](https://doc.rust-lang.org/book/ch19-06-macros.html) +- [The Little Book of Rust Macros](https://veykril.github.io/tlborm/) diff --git a/exercises/21_macros/macros1.rs b/exercises/21_macros/macros1.rs new file mode 100644 index 0000000..fb3c3ff --- /dev/null +++ b/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/exercises/21_macros/macros2.rs b/exercises/21_macros/macros2.rs new file mode 100644 index 0000000..2d9dec7 --- /dev/null +++ b/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/exercises/21_macros/macros3.rs b/exercises/21_macros/macros3.rs new file mode 100644 index 0000000..9537494 --- /dev/null +++ b/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/exercises/21_macros/macros4.rs b/exercises/21_macros/macros4.rs new file mode 100644 index 0000000..9d77f6a --- /dev/null +++ b/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/exercises/22_clippy/README.md b/exercises/22_clippy/README.md new file mode 100644 index 0000000..55438af --- /dev/null +++ b/exercises/22_clippy/README.md @@ -0,0 +1,10 @@ +# Clippy + +The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code. + +If you used the installation script for Rustlings, Clippy should be already installed. +If not you can install it manually via `rustup component add clippy`. + +## Further information + +- [GitHub Repository](https://github.com/rust-lang/rust-clippy). diff --git a/exercises/22_clippy/clippy1.rs b/exercises/22_clippy/clippy1.rs new file mode 100644 index 0000000..7165da4 --- /dev/null +++ b/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/exercises/22_clippy/clippy2.rs b/exercises/22_clippy/clippy2.rs new file mode 100644 index 0000000..8cfe6f8 --- /dev/null +++ b/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/exercises/22_clippy/clippy3.rs b/exercises/22_clippy/clippy3.rs new file mode 100644 index 0000000..4f78834 --- /dev/null +++ b/exercises/22_clippy/clippy3.rs @@ -0,0 +1,27 @@ +// 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<()> = None; + 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/exercises/23_conversions/README.md b/exercises/23_conversions/README.md new file mode 100644 index 0000000..619a78c --- /dev/null +++ b/exercises/23_conversions/README.md @@ -0,0 +1,23 @@ +# Type conversions + +Rust offers a multitude of ways to convert a value of a given type into another type. + +The simplest form of type conversion is a type cast expression. It is denoted with the binary operator `as`. For instance, `println!("{}", 1 + 1.0);` would not compile, since `1` is an integer while `1.0` is a float. However, `println!("{}", 1 as f32 + 1.0)` should compile. The exercise [`using_as`](using_as.rs) tries to cover this. + +Rust also offers traits that facilitate type conversions upon implementation. These traits can be found under the [`convert`](https://doc.rust-lang.org/std/convert/index.html) module. +The traits are the following: + +- `From` and `Into` covered in [`from_into`](from_into.rs) +- `TryFrom` and `TryInto` covered in [`try_from_into`](try_from_into.rs) +- `AsRef` and `AsMut` covered in [`as_ref_mut`](as_ref_mut.rs) + +Furthermore, the `std::str` module offers a trait called [`FromStr`](https://doc.rust-lang.org/std/str/trait.FromStr.html) which helps with converting strings into target types via the `parse` method on strings. If properly implemented for a given type `Person`, then `let p: Person = "Mark,20".parse().unwrap()` should both compile and run without panicking. + +These should be the main ways ***within the standard library*** to convert data into your desired types. + +## Further information + +These are not directly covered in the book, but the standard library has a great documentation for it. + +- [conversions](https://doc.rust-lang.org/std/convert/index.html) +- [`FromStr` trait](https://doc.rust-lang.org/std/str/trait.FromStr.html) diff --git a/exercises/23_conversions/as_ref_mut.rs b/exercises/23_conversions/as_ref_mut.rs new file mode 100644 index 0000000..54f0cd1 --- /dev/null +++ b/exercises/23_conversions/as_ref_mut.rs @@ -0,0 +1,61 @@ +// 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. +// TODO: Add the `AsRef` trait appropriately as a trait bound. +fn byte_counter(arg: T) -> usize { + arg.as_ref().as_bytes().len() +} + +// Obtain the number of characters (not bytes) in the given argument. +// TODO: Add the `AsRef` trait appropriately as a trait bound. +fn char_counter(arg: T) -> usize { + arg.as_ref().chars().count() +} + +// Squares a number using `as_mut()`. +// TODO: Add the appropriate trait bound. +fn num_sq(arg: &mut T) { + // TODO: Implement the function body. +} + +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/exercises/23_conversions/from_into.rs b/exercises/23_conversions/from_into.rs new file mode 100644 index 0000000..bc2783a --- /dev/null +++ b/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/exercises/23_conversions/from_str.rs b/exercises/23_conversions/from_str.rs new file mode 100644 index 0000000..4b1aaa2 --- /dev/null +++ b/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 `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 +// 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/exercises/23_conversions/try_from_into.rs b/exercises/23_conversions/try_from_into.rs new file mode 100644 index 0000000..f3ae80a --- /dev/null +++ b/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/exercises/23_conversions/using_as.rs b/exercises/23_conversions/using_as.rs new file mode 100644 index 0000000..c131d1f --- /dev/null +++ b/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/exercises/README.md b/exercises/README.md new file mode 100644 index 0000000..237f2f1 --- /dev/null +++ b/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 | §19.5 | +| clippy | §21.4 | +| conversions | n/a | diff --git a/exercises/quizzes/README.md b/exercises/quizzes/README.md new file mode 100644 index 0000000..4d3bcd9 --- /dev/null +++ b/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/exercises/quizzes/quiz1.rs b/exercises/quizzes/quiz1.rs new file mode 100644 index 0000000..04fb2aa --- /dev/null +++ b/exercises/quizzes/quiz1.rs @@ -0,0 +1,31 @@ +// 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! + +// TODO: Write a function that calculates the price of an order of apples given +// the quantity bought. +// fn calculate_price_of_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/exercises/quizzes/quiz2.rs b/exercises/quizzes/quiz2.rs new file mode 100644 index 0000000..2cddba9 --- /dev/null +++ b/exercises/quizzes/quiz2.rs @@ -0,0 +1,63 @@ +// 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: ???) -> ??? { ??? } +} + +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; + + #[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/exercises/quizzes/quiz3.rs b/exercises/quizzes/quiz3.rs new file mode 100644 index 0000000..c877c5f --- /dev/null +++ b/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: f32, + 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/solutions/00_intro/intro1.rs b/solutions/00_intro/intro1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/00_intro/intro1.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/solutions/00_intro/intro2.rs b/solutions/00_intro/intro2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/00_intro/intro2.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/solutions/01_variables/variables1.rs b/solutions/01_variables/variables1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/01_variables/variables1.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/solutions/01_variables/variables2.rs b/solutions/01_variables/variables2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/01_variables/variables2.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/solutions/01_variables/variables3.rs b/solutions/01_variables/variables3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/01_variables/variables3.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/solutions/01_variables/variables4.rs b/solutions/01_variables/variables4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/01_variables/variables4.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/solutions/01_variables/variables5.rs b/solutions/01_variables/variables5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/01_variables/variables5.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/solutions/01_variables/variables6.rs b/solutions/01_variables/variables6.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/01_variables/variables6.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/solutions/02_functions/functions1.rs b/solutions/02_functions/functions1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/02_functions/functions1.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/solutions/02_functions/functions2.rs b/solutions/02_functions/functions2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/02_functions/functions2.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/solutions/02_functions/functions3.rs b/solutions/02_functions/functions3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/02_functions/functions3.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/solutions/02_functions/functions4.rs b/solutions/02_functions/functions4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/02_functions/functions4.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/solutions/02_functions/functions5.rs b/solutions/02_functions/functions5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/02_functions/functions5.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/solutions/03_if/if1.rs b/solutions/03_if/if1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/03_if/if1.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/solutions/03_if/if2.rs b/solutions/03_if/if2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/03_if/if2.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/solutions/03_if/if3.rs b/solutions/03_if/if3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/03_if/if3.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/solutions/04_primitive_types/primitive_types1.rs b/solutions/04_primitive_types/primitive_types1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types1.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/solutions/04_primitive_types/primitive_types2.rs b/solutions/04_primitive_types/primitive_types2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types2.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/solutions/04_primitive_types/primitive_types3.rs b/solutions/04_primitive_types/primitive_types3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types3.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/solutions/04_primitive_types/primitive_types4.rs b/solutions/04_primitive_types/primitive_types4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types4.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/solutions/04_primitive_types/primitive_types5.rs b/solutions/04_primitive_types/primitive_types5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types5.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/solutions/04_primitive_types/primitive_types6.rs b/solutions/04_primitive_types/primitive_types6.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/04_primitive_types/primitive_types6.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/solutions/05_vecs/vecs1.rs b/solutions/05_vecs/vecs1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/05_vecs/vecs1.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/solutions/05_vecs/vecs2.rs b/solutions/05_vecs/vecs2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/05_vecs/vecs2.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/solutions/06_move_semantics/move_semantics1.rs b/solutions/06_move_semantics/move_semantics1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/06_move_semantics/move_semantics1.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/solutions/06_move_semantics/move_semantics2.rs b/solutions/06_move_semantics/move_semantics2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/06_move_semantics/move_semantics2.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/solutions/06_move_semantics/move_semantics3.rs b/solutions/06_move_semantics/move_semantics3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/06_move_semantics/move_semantics3.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/solutions/06_move_semantics/move_semantics4.rs b/solutions/06_move_semantics/move_semantics4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/06_move_semantics/move_semantics4.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/solutions/06_move_semantics/move_semantics5.rs b/solutions/06_move_semantics/move_semantics5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/06_move_semantics/move_semantics5.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/solutions/07_structs/structs1.rs b/solutions/07_structs/structs1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/07_structs/structs1.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/solutions/07_structs/structs2.rs b/solutions/07_structs/structs2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/07_structs/structs2.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/solutions/07_structs/structs3.rs b/solutions/07_structs/structs3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/07_structs/structs3.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/solutions/08_enums/enums1.rs b/solutions/08_enums/enums1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/08_enums/enums1.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/solutions/08_enums/enums2.rs b/solutions/08_enums/enums2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/08_enums/enums2.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/solutions/08_enums/enums3.rs b/solutions/08_enums/enums3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/08_enums/enums3.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/solutions/09_strings/strings1.rs b/solutions/09_strings/strings1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/09_strings/strings1.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/solutions/09_strings/strings2.rs b/solutions/09_strings/strings2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/09_strings/strings2.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/solutions/09_strings/strings3.rs b/solutions/09_strings/strings3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/09_strings/strings3.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/solutions/09_strings/strings4.rs b/solutions/09_strings/strings4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/09_strings/strings4.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/solutions/10_modules/modules1.rs b/solutions/10_modules/modules1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/10_modules/modules1.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/solutions/10_modules/modules2.rs b/solutions/10_modules/modules2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/10_modules/modules2.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/solutions/10_modules/modules3.rs b/solutions/10_modules/modules3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/10_modules/modules3.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/solutions/11_hashmaps/hashmaps1.rs b/solutions/11_hashmaps/hashmaps1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/11_hashmaps/hashmaps1.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/solutions/11_hashmaps/hashmaps2.rs b/solutions/11_hashmaps/hashmaps2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/11_hashmaps/hashmaps2.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/solutions/11_hashmaps/hashmaps3.rs b/solutions/11_hashmaps/hashmaps3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/11_hashmaps/hashmaps3.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/solutions/12_options/options1.rs b/solutions/12_options/options1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/12_options/options1.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/solutions/12_options/options2.rs b/solutions/12_options/options2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/12_options/options2.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/solutions/12_options/options3.rs b/solutions/12_options/options3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/12_options/options3.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/solutions/13_error_handling/errors1.rs b/solutions/13_error_handling/errors1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/13_error_handling/errors1.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/solutions/13_error_handling/errors2.rs b/solutions/13_error_handling/errors2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/13_error_handling/errors2.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/solutions/13_error_handling/errors3.rs b/solutions/13_error_handling/errors3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/13_error_handling/errors3.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/solutions/13_error_handling/errors4.rs b/solutions/13_error_handling/errors4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/13_error_handling/errors4.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/solutions/13_error_handling/errors5.rs b/solutions/13_error_handling/errors5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/13_error_handling/errors5.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/solutions/13_error_handling/errors6.rs b/solutions/13_error_handling/errors6.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/13_error_handling/errors6.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/solutions/14_generics/generics1.rs b/solutions/14_generics/generics1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/14_generics/generics1.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/solutions/14_generics/generics2.rs b/solutions/14_generics/generics2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/14_generics/generics2.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/solutions/15_traits/traits1.rs b/solutions/15_traits/traits1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/15_traits/traits1.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/solutions/15_traits/traits2.rs b/solutions/15_traits/traits2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/15_traits/traits2.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/solutions/15_traits/traits3.rs b/solutions/15_traits/traits3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/15_traits/traits3.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/solutions/15_traits/traits4.rs b/solutions/15_traits/traits4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/15_traits/traits4.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/solutions/15_traits/traits5.rs b/solutions/15_traits/traits5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/15_traits/traits5.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/solutions/16_lifetimes/lifetimes1.rs b/solutions/16_lifetimes/lifetimes1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/16_lifetimes/lifetimes1.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/solutions/16_lifetimes/lifetimes2.rs b/solutions/16_lifetimes/lifetimes2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/16_lifetimes/lifetimes2.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/solutions/16_lifetimes/lifetimes3.rs b/solutions/16_lifetimes/lifetimes3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/16_lifetimes/lifetimes3.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/solutions/17_tests/tests1.rs b/solutions/17_tests/tests1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/17_tests/tests1.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/solutions/17_tests/tests2.rs b/solutions/17_tests/tests2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/17_tests/tests2.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/solutions/17_tests/tests3.rs b/solutions/17_tests/tests3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/17_tests/tests3.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/solutions/18_iterators/iterators1.rs b/solutions/18_iterators/iterators1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/18_iterators/iterators1.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/solutions/18_iterators/iterators2.rs b/solutions/18_iterators/iterators2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/18_iterators/iterators2.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/solutions/18_iterators/iterators3.rs b/solutions/18_iterators/iterators3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/18_iterators/iterators3.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/solutions/18_iterators/iterators4.rs b/solutions/18_iterators/iterators4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/18_iterators/iterators4.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/solutions/18_iterators/iterators5.rs b/solutions/18_iterators/iterators5.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/18_iterators/iterators5.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/solutions/19_smart_pointers/arc1.rs b/solutions/19_smart_pointers/arc1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/19_smart_pointers/arc1.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/solutions/19_smart_pointers/box1.rs b/solutions/19_smart_pointers/box1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/19_smart_pointers/box1.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/solutions/19_smart_pointers/cow1.rs b/solutions/19_smart_pointers/cow1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/19_smart_pointers/cow1.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/solutions/19_smart_pointers/rc1.rs b/solutions/19_smart_pointers/rc1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/19_smart_pointers/rc1.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/solutions/20_threads/threads1.rs b/solutions/20_threads/threads1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/20_threads/threads2.rs b/solutions/20_threads/threads2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/20_threads/threads3.rs b/solutions/20_threads/threads3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/21_macros/macros1.rs b/solutions/21_macros/macros1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/21_macros/macros2.rs b/solutions/21_macros/macros2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/21_macros/macros3.rs b/solutions/21_macros/macros3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/21_macros/macros4.rs b/solutions/21_macros/macros4.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/22_clippy/clippy1.rs b/solutions/22_clippy/clippy1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/22_clippy/clippy2.rs b/solutions/22_clippy/clippy2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/22_clippy/clippy3.rs b/solutions/22_clippy/clippy3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/23_conversions/as_ref_mut.rs b/solutions/23_conversions/as_ref_mut.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/23_conversions/from_into.rs b/solutions/23_conversions/from_into.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/23_conversions/from_str.rs b/solutions/23_conversions/from_str.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/23_conversions/try_from_into.rs b/solutions/23_conversions/try_from_into.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/23_conversions/using_as.rs b/solutions/23_conversions/using_as.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/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/solutions/README.md b/solutions/README.md new file mode 100644 index 0000000..5b5176b --- /dev/null +++ b/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/solutions/quizzes/quiz1.rs b/solutions/quizzes/quiz1.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/quizzes/quiz1.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/solutions/quizzes/quiz2.rs b/solutions/quizzes/quiz2.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/quizzes/quiz2.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/solutions/quizzes/quiz3.rs b/solutions/quizzes/quiz3.rs new file mode 100644 index 0000000..dcf2377 --- /dev/null +++ b/solutions/quizzes/quiz3.rs @@ -0,0 +1,4 @@ +fn main() { + // DON'T EDIT THIS SOLUTION FILE! + // It will be automatically filled after you finish the exercise. +}