From d078910cbedb4696924094a9dd900c1a48405d3d Mon Sep 17 00:00:00 2001 From: Daniel Heras Quesada Date: Wed, 13 Nov 2024 00:20:16 +0100 Subject: [PATCH] feat: couple more lessons --- src/controlflow.rs | 41 +++++++++++++++++++ .../{medium.rs => medium_difficulty.rs} | 0 src/functions.rs | 17 ++++++++ src/main.rs | 6 ++- 4 files changed, 62 insertions(+), 2 deletions(-) rename src/exercises/{medium.rs => medium_difficulty.rs} (100%) create mode 100644 src/functions.rs diff --git a/src/controlflow.rs b/src/controlflow.rs index c214261..4e11b97 100644 --- a/src/controlflow.rs +++ b/src/controlflow.rs @@ -195,4 +195,45 @@ pub fn control_flow_module() { n @ 1..5 => println!("{n} is between 1 and 5"), _ => (), } + + // If let + // Lets you simplify destructuring + // Usefull if objecto neither implements nor derives PartialEq (cant do variable == Object::A) + if let n @ 1..5 = another_number { + println!("{n} is between 1 and 5"); + } + + // can also be used to match an enum + enum Fooo { + A, + B, + Another(u32), + }; + + let a = Fooo::A; + let b = Fooo::Another(3); + + if let Fooo::A = a { + println!("a is A"); + } + + if let Fooo::Another(n) = b { + println!("b is another({n})"); + } + + // Let else + // Acts as a try - catch when delcaring variables + + // while let + // Similar to if let, to make match sequences more tolerable + let mut optional = Some(0); + + while let Some(i) = optional { + if i > 9 { + println!("Greater than 9"); + optional = None; + } else { + optional = Some(i + 1); + } + } } diff --git a/src/exercises/medium.rs b/src/exercises/medium_difficulty.rs similarity index 100% rename from src/exercises/medium.rs rename to src/exercises/medium_difficulty.rs diff --git a/src/functions.rs b/src/functions.rs new file mode 100644 index 0000000..42c54bc --- /dev/null +++ b/src/functions.rs @@ -0,0 +1,17 @@ +fn fizzbuzz(n: i32) { + for i in 1..=n { + if i % 15 == 0 { + println!("FizzBuzz"); + } else if i % 5 == 0 { + println!("Buzz"); + } else if i % 3 == 0 { + println!("Fizz"); + } else { + println!("{i}"); + } + } +} + +pub fn functions_module() { + fizzbuzz(10); +} diff --git a/src/main.rs b/src/main.rs index f27c426..819700f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,8 @@ //mod conversion; // mod controlflow; // mod traits; -mod str_types; +// mod str_types; +mod functions; fn main() { // helloworld::hello_world_module(); @@ -24,5 +25,6 @@ fn main() { //conversion::conversion_module(); // controlflow::control_flow_module(); //traits::traits_exercise(); - str_types::str_types_module(); + // str_types::str_types_module(); + functions::functions_module(); }