Rust Branching - if let, match

Поділитися
Вставка
  • Опубліковано 1 лис 2024

КОМЕНТАРІ • 140

  • @JakobKenda
    @JakobKenda Рік тому +28

    the real power of pattern matching really shows when destructuring complex structs or slices. i am writing a compiler in rust and the pattern matching makes conditionals very readable

    • @codetothemoon
      @codetothemoon  Рік тому +2

      nice what type of compiler are you writing? Something for an existing language or for a new one?

    • @AndrewBrownK
      @AndrewBrownK Рік тому +3

      EXACTLY. Always sorely disappointed when languages get so close but so, so far. (Looking at you, Kotlin)

    • @ewertonls_
      @ewertonls_ Рік тому

      @@AndrewBrownK looking at kotlin, looking at dart 3.x

    • @diadetediotedio6918
      @diadetediotedio6918 Рік тому +2

      Precisely, rust has a wonderful pattern matching. I created my own text tokenization crate in the language and working with it using pattern matching is extremely simple, you just need to be expressive and concise and the logical structures unfold naturally.

  • @benjamingrant6869
    @benjamingrant6869 Рік тому +6

    I have really grown to love the new let else construct. I found it very useful when manually writing a parser.

    • @codetothemoon
      @codetothemoon  Рік тому +2

      this actually wasn't on my radar when I was making the video, I wish I had included it!

    • @Yadobler
      @Yadobler Рік тому

      @@codetothemoon I have a question, is it wrong to say that "if let" is similar to python walrus operator (:=) in that it evaluates the rhs expression and then if it is of the type ok(x) then the condition is met
      if let ok(x) = getBobMood() { print("mood is {}", x); }
      vs
      if (x := getBobMood()) is not None: print(r"mood is {x}")
      Im guessing the difference is in rust enum and how ok(x) itself is a type of Result but x can is set? is that it?
      Gosh I think the main confusion here is in how Rust defines Enums, and how enums can have data in them

  • @mageprometheus
    @mageprometheus Рік тому +29

    Thanks, good lesson. If I need to take my phone with me, it's hardly used. Welcome to the world of happily unplugged people. 😄

    • @codetothemoon
      @codetothemoon  Рік тому +7

      thanks, glad you liked it. props for staying unplugged, that requires willpower that many don't have 😎

    • @CliveStewart-bq3od
      @CliveStewart-bq3od Рік тому +1

      So how did you watch the video ? am just curious

    • @mageprometheus
      @mageprometheus Рік тому +1

      @@CliveStewart-bq3od My lounge is 50% recording studio for music. I have broadband and watch Videos that I choose but avoid social media. For me, getting into the creative flow requires isolation and that's hard with any kind of tech addiction.

  • @thisisscotts
    @thisisscotts Рік тому +1

    I used my first "if let" today because I remembered this video from a few months ago.
    Thanks!

  • @Nintron
    @Nintron Рік тому +9

    That intro is fantastic

    • @codetothemoon
      @codetothemoon  Рік тому +3

      thanks, I actually almost trimmed it out right before publishing lol

    • @_aurora60
      @_aurora60 8 місяців тому +1

      @@codetothemoonI literally subscribed because of that intro :D thanks for not trimming it!

  • @havocthehobbit
    @havocthehobbit Місяць тому +1

    First few seconds of this vid, resonated with me on a , 'bro are you stalking me' , kind of level 😅

  • @sergiuoanes4635
    @sergiuoanes4635 Рік тому +6

    Nice job as always! Super happy to see this kind of videos. Helps me a lot learning Rust.

  • @Im_Ninooo
    @Im_Ninooo 5 місяців тому

    being able to specify a condition is so helpful! I didn't know I could do that!

  • @seannewell397
    @seannewell397 Рік тому +2

    The unwrap_or is class, love to see proper error handling. More!

  • @SpektralJo
    @SpektralJo Рік тому +1

    Yes I am absolutely watching this sitting on the

  • @alexdai_
    @alexdai_ Рік тому +1

    Really cool explanation, short but informative.

  • @hellovova
    @hellovova Рік тому +3

    It would be nice to explain if let more deeply, what is it, why do we need it, what is benefits of using it, what is it's equivalency in "normal" coding . I know you can, I remember your great explanation of macros. Like from me.

    • @codetothemoon
      @codetothemoon  Рік тому

      thanks for the feedback! I definitely could have explored the "why" a bit more.

  • @echobucket
    @echobucket Рік тому +7

    Wow that font is big.

  • @Ma1ne2
    @Ma1ne2 Рік тому +5

    Really cool video as usual! Would have been nice to see the moods as an enum and show how powerful they're together with match statements, but I understand then it wouldn't have been as straight forward to explain guards :)

    • @codetothemoon
      @codetothemoon  Рік тому +1

      ahh good point, yeah I suppose I could have done it that way too!

  • @phenanrithe
    @phenanrithe Рік тому +6

    "if let" is a nice tool! I often miss the guard feature we have with "match", however, never understood why it has never been accepted ("if let Ok(res) && !res.is_empty()" for example). Without it, "match" can still be used instead, though I just find it less clear about the binary nature of the test.

    • @jrmoulton
      @jrmoulton Рік тому +2

      From what I've read and remember it is just the current state of the implementation. There are tracking issues for this very thing and it could be added if it was implemented

    • @Turalcar
      @Turalcar 9 місяців тому

      I'd probably go With "if let Ok(res) if !res.is_empty()" for grammar which looks a bit silly

  • @CliveStewart-bq3od
    @CliveStewart-bq3od Рік тому

    Yep you got that phone thing right! love it.

  • @sergioquijanorey7426
    @sergioquijanorey7426 Рік тому +20

    I don't know if other people thinks the same, but for me if let statement is less clear than using match statement for doing the same. Using your example, it would be:
    ```
    let boob_mood = match get_result {
    Ok(mood) => {
    println!("got value from the database");
    mood
    },
    Err(error) => {
    println!("Couldn't get the value from the database");
    println!("Err code was: {error:?}");
    String::from("Neutral")
    }
    };
    ```
    It's clearer because I see that I do something when I got Ok, other thing when I got Err. Also, I got which is the value hold into the Err type, and I can do some logs, transforms or just raise the error directly.
    I am alone in this? Are there some good reasons why if let is superior (because I see that a lot more than the snippet I wrote)

    • @AndrewBrownK
      @AndrewBrownK Рік тому +9

      One isn’t “superior” to the other but generally I use match for exhaustive matching or expressions, and I pretty much save if let for conditional effects or mutations that are not expressions. I’d scratch my head in confusion if someone used “if let { … } else { … }” though

    • @Ruhrpottpatriot
      @Ruhrpottpatriot Рік тому +9

      if-let and it's sibling let-else are great if you need to handle a particular case and don't care about the others. While in the case of Option or Result there isn't much benefit, it gets much cleaner if you have, say an HTTP Error code enum. If you wanted to calculate a value based on the code and and return it from the block your match statement would need to compute a dummy value or you'd need to use an option (which you need to destructure or pass along with ?.

    • @Ruhrpottpatriot
      @Ruhrpottpatriot Рік тому +6

      @@AndrewBrownK For these cases the new let-else statement would probably be better since we could just write
      ```
      let Some(mood) = con.get("bob:mood) else {
      // Do stuff for the error/none case
      }
      ```

    • @sergioquijanorey7426
      @sergioquijanorey7426 Рік тому

      @@Ruhrpottpatriot thanks, great example, I see the point 😊

    • @AndrewBrownK
      @AndrewBrownK Рік тому

      @@Ruhrpottpatriot ooh I do have to admit I like that. yeah circumstantial formatting is probably a good factor to consider in any situation

  • @erlangparasu6339
    @erlangparasu6339 Рік тому +1

    thankyou so much 🙏👍

  • @edgeeffect
    @edgeeffect Рік тому +1

    Oooh.... you got a nice big font! - thanks! :)

  • @AndrewBrownK
    @AndrewBrownK Рік тому +2

    Let's not forget the lovely "while let"

    • @codetothemoon
      @codetothemoon  Рік тому

      ahh yes, I probably should have covered that in this video too!

  • @theroboman727
    @theroboman727 Рік тому +7

    Maybe `let else` would have fit into this video nicely as well?

    • @codetothemoon
      @codetothemoon  Рік тому

      probably should have included this as well!

  • @yousefsaddeek
    @yousefsaddeek 4 місяці тому +1

    very good explanation i just subscribed

    • @codetothemoon
      @codetothemoon  4 місяці тому

      thank you, very happy to have you onboard!

  • @Zeioth
    @Zeioth 7 місяців тому

    Pretty good video! It would have been cool explaining Some => and None => which are quite common patterns.

  • @jakubrembiasz8942
    @jakubrembiasz8942 Рік тому +1

    Great vid!

  • @mr.norris3840
    @mr.norris3840 Рік тому +3

    3:50 Your password is visible!

    • @codetothemoon
      @codetothemoon  Рік тому +2

      thanks for pointing this out - fortunately this particular database is long gone :)

  • @guilherme5094
    @guilherme5094 Рік тому +1

    Thanks man👍!

  • @theroboman727
    @theroboman727 Рік тому +7

    cool video, but I have one gripe with it. I feel like the database thingy might throw off some beginners, because its inaccessible.
    Setting that up is kind of a big commitment, and beginner might not be able to find the relevant documentation very quickly. It's important to be able to see at least the function signature of everything you're doing and to be able to experiment with it I think.
    Another small gripe I've had across multiple videos is that you don't really show the terminal error messages. IDE error messages are often shortened and are missing a lot of info that you would get in the terminal, so I often tell beginners to always go run cargo check in the terminal when its not immediately obvious what you should do to fix an error message.
    A great example of this is No Boilerplate's video "Rust Is Easy", where they take a javascript function and convert it to rust based on only the compiler's suggestions.
    So maybe when an error message is vague, pull up the terminal and run cargo check, instead of explaining it with your own hindsight. that would be nice.
    Love your videos overall.

    • @vinos1629
      @vinos1629 Рік тому

      I feel like you really shouldnt be getting into rust if you cant understand a database connection or even how to connect to a database

    • @theroboman727
      @theroboman727 Рік тому

      @@vinos1629 you dont need databases for everything though? Im pretty decent with rust, and have written tools that are in active use in a community, but they do not need to store any data other than simple settings on the user's computer. I am just a hobbyist though, and should learn what databases are about at some point.
      My point was also not really exclusive to databases.

    • @phenanrithe
      @phenanrithe Рік тому +1

      That was my feeling too. It felt the presentation was made more confusing with repeated excuses about this part of the code "to be please ignored", and this was not really necessary in the first place. On the other hand it shows other features that may awake the curiosity of the viewer. I think that's the sort of example I'd use in a book (with appropriate introduction and links) when the reader has the time, but I would avoid it in short videos because people are watching them to save time. Just got me a raised eyebrow though, not a big deal in an overall great video.

    • @codetothemoon
      @codetothemoon  Рік тому +4

      thanks for the great feedback @theroboman727 ! Yeah I wasn't sure I the database thing was a good call, I was hoping a more "realistic" example might intrigue people a bit more. But then I used completely contrived data in said database, and probably thwarted my own aim for realism 🙃
      Re: showing terminal error messages, this is a great suggestion, I may implement this!

    • @erikyoung5139
      @erikyoung5139 Рік тому

      @@codetothemoon I find all your videos extremely helpful and well done, but am with @theroboman727 on this

  • @Pyro2352
    @Pyro2352 Рік тому +1

    Thank you, sir, for the video. Keep up the excellent work. You are helping in a real meaningful way.
    Could you do a video on debugging and perhaps setting up your IDE debugger to see the content of a vector when using breakpoints?
    I'm using Clion and I'm struggling with the setup and with efficient debugging in general.

    • @codetothemoon
      @codetothemoon  Рік тому +1

      really happy that these videos are of help! I actually haven't delved too deeply into debugging Rust. I'm more of a "debug via log output" type, primarily because of how live debugging tends to cause network timeouts

    • @Pyro2352
      @Pyro2352 Рік тому

      @@codetothemoon
      I usually don’t work with networking, so I haven’t thought of the timeout issues, but in that case, it makes total sense.
      At work we use Python, so I got used to live debugging mainly because of the dynamic typing.
      In a case that something breaks, the quickest way for me to understand function argument types, call structure and class methods, that are inherited from who knows where was with live debugger.
      In Rust, I guess it is not as needed thanks to the type system, but I still find it very convenient.

  • @naranyala_dev
    @naranyala_dev Рік тому +1

    when watching on desktop, I need to make it a small size of my browser

    • @codetothemoon
      @codetothemoon  Рік тому

      hah! it's hard to cater to both desktop and mobile...

  • @OrtinFargo
    @OrtinFargo Рік тому +1

    I think I just been called out the first 5 seconds of the vid XD

  • @kdmtv8188
    @kdmtv8188 Рік тому +1

    Another nice one, Please what's the name of this IDE?

    • @codetothemoon
      @codetothemoon  Рік тому +1

      thank you! DOOM emacs. might do a video on it at some point.

    • @kdmtv8188
      @kdmtv8188 Рік тому

      @@codetothemoon it would be great to see that happen

  • @Bvngee
    @Bvngee Рік тому +3

    Im fascinated about your editor choice!! I know you've at least used VSCode, neovim, helix, and now doom emacs?? What's your reasoning and/or what have you learned?

    • @codetothemoon
      @codetothemoon  Рік тому +2

      haha yeah last year was my year of experimenting with different editors. settled on doom emacs for the foreseeable future. there'll be a video on it at some point, once I'm able to adequately articulate my reasoning. The short answer is - org mode, literate programming, dired, and the M-x menu. I think much of this can be replicated in something like Neovim but I'm not entirely clear yet on where the limit is there.

    • @Bvngee
      @Bvngee Рік тому +1

      @@codetothemoon I would absolutely love a video on this. I started with neovim a while ago but there's always more and more work to do to keep it up to date, and I never quite feel like I'm "there" yet. Let alone not even being sure if neovim is the right choice! Anyways, love the content!

    • @exsesx
      @exsesx Рік тому

      @@codetothemoon How did you make it look so good? I definitely need that video. What's the font you're using, by the way?

  • @lamka02sk
    @lamka02sk Рік тому +3

    Is there a way to easily access the error struct in else block?

    • @codetothemoon
      @codetothemoon  Рік тому +3

      I think the easiest way would be to add "if let Err(e)" after the else keyword.

    • @theroboman727
      @theroboman727 Рік тому +3

      ​@@codetothemoon you can do `else if let Err(e)`. But `if let` is only really meant for checking one case and ignoring the rest. in more complex cases like this you should use `match`

  • @plrpilot
    @plrpilot Рік тому +2

    Hahaha. As I sit on a plane watching this on my phone….

    • @codetothemoon
      @codetothemoon  Рік тому +2

      Bet the big font came in handy! 🙃

    • @plrpilot
      @plrpilot Рік тому

      @@codetothemoon it was perfect. But honestly, your videos always are. You do a great job.

  • @DeHSIFY
    @DeHSIFY Рік тому +2

    Can you please post your doom emacs config?

    • @codetothemoon
      @codetothemoon  Рік тому

      There's nothing particularly special in there (at least that is relevant to what you're seeing here), i just uncommented rust in init.el and changed the theme to monokai-pro

  • @JorgetePanete
    @JorgetePanete Рік тому

    how do we normalize utf8? i recently read about an example: é vs e + "combining accent" character, they are visually the same but different bytes, swift normalizes by default

    • @Turalcar
      @Turalcar 9 місяців тому +1

      You use unicode-normalization crate

  • @noviriustomeisho6630
    @noviriustomeisho6630 Рік тому +2

    What is the configuration for your highlight syntax?

  • @wolfboyft
    @wolfboyft Рік тому

    3:48 is where i got lost.
    What exactly is happening when `if let Ok(res) = get_result` is run?

    • @wolfboyft
      @wolfboyft Рік тому

      Somebody else told me the syntax is meaningless and could be anything. That helps.

  • @patrick1532
    @patrick1532 Рік тому +1

    What keyboard do you use? It sounds nice.

    • @codetothemoon
      @codetothemoon  Рік тому

      Thanks! it's a Corne v3 with Gateron Pro Red switches. Might be the topic of a video at some point.

  • @AbhishekBajpaiHere
    @AbhishekBajpaiHere Рік тому +1

    You gave up on helix and switched to DOOM Emacs ? How is your experience ?

    • @codetothemoon
      @codetothemoon  Рік тому

      still love helix, can't really go all in on it until they have plugin support though. DOOM is amazing, especially org mode and literate programming. No plans to switch away from it anytime soon.

  • @konstantinrebrov675
    @konstantinrebrov675 Рік тому

    How are you putting images inline the code?

  • @durchschnittlich
    @durchschnittlich Рік тому +1

    Your keyboard sounds so incredibly nice! What are you using?

    • @codetothemoon
      @codetothemoon  Рік тому

      Thanks! It's a Corne with Gateron Red Pro switches. shop.beekeeb.com/product/pre-soldered-crkbd-v3-mx-corne-keyboard/

    • @bottlerocketlabs
      @bottlerocketlabs Рік тому

      @@codetothemoon do you have a link to the keyboard layout you are using? Just curious

  • @repe0
    @repe0 Рік тому +1

    Storing password in env variable but then printing connection string including the password in next line?

    • @codetothemoon
      @codetothemoon  Рік тому

      yeah, wouldn't do that in production code. I'll know I forgot to rotate my passwords when AWS bills skyrocket 🙃

  • @kamertonaudiophileplayer847
    @kamertonaudiophileplayer847 7 місяців тому

    if let looks quite powerful and concise operator. However it isn't natively obvious.

  • @linuswalker4552
    @linuswalker4552 Рік тому +1

    can I get your nvim config? I use arch btw.

    • @codetothemoon
      @codetothemoon  Рік тому +1

      I'm actually using DOOM emacs in this video!

    • @linuswalker4552
      @linuswalker4552 Рік тому

      @@codetothemoon thanks, I didn't notice that. and can you make a video about web3 and how to start with rust? Thanks again.

  • @TheInspctrcat
    @TheInspctrcat Рік тому +1

    Which font do you use?

  • @romanstingler435
    @romanstingler435 Рік тому +1

    1sec in my head screams WAY TOO BIG

    • @codetothemoon
      @codetothemoon  Рік тому

      i've finally gone too far in the opposite direction, usually the problem is that it looks too small in video even though it looked fine during recording...

  • @JosephDalrymple
    @JosephDalrymple Рік тому +1

    New keyboard? :D

    • @codetothemoon
      @codetothemoon  Рік тому

      Relatively new, it's a Corne github.com/foostan/crkbd

    • @JosephDalrymple
      @JosephDalrymple Рік тому

      @@codetothemoon Nice! I've heard a lot about them, and I've been tempted, but I haven't made up my mind yet haha.
      How do you like yours?

    • @codetothemoon
      @codetothemoon  Рік тому +1

      @@JosephDalrymple It's incredible. But now I'm using a Chocofi because I realized I like home row mods and so I don't need the 3 outermost keys on each side anymore, so now I'm using a 36 key layout. Still going to be using the Corne (probably in all videos for the foreseeable future), just not the outermost key columns

  • @justalawngnome7404
    @justalawngnome7404 Рік тому +1

    Hey hey, looks like somebody’s learning Emacs.

    • @codetothemoon
      @codetothemoon  Рік тому

      indeed! is my newbie status that obvious?

    • @justalawngnome7404
      @justalawngnome7404 Рік тому

      @@codetothemoon Haha, not really. I mean sure, you occasionally pause when switching out of INSERT mode, but I'd say you're past the point of being as fast with Doom Emacs as with any other editor. It's all downhill from here, man!
      A cool tip in case you haven't discovered it yet: use "Ctrl+[" instead of "ESC" to move out of INSERT mode. It works out of the box and doesn't require you to leave your home row.

  • @LALO-cv4ck
    @LALO-cv4ck Рік тому +1

    what font :))

  • @HyperCodec
    @HyperCodec Рік тому +2

    Lmao the debug showed the password

  • @scwan-ew8uh
    @scwan-ew8uh Рік тому

    Rust influxdb2

  • @i007c
    @i007c Рік тому

    why did you log the password 🤣🐧

  • @Sahil-a-vim-user
    @Sahil-a-vim-user Рік тому +2

    It would make your videos much more engaging if you can remove the typing and just show the code, just highlight the part you added. This will decrease the video length but actually makes for much more interesting videos. The video was good, never knew about if statement inside the match clause. Keep up the good work.

    • @codetothemoon
      @codetothemoon  Рік тому +3

      thanks - i've gone back and forth on this and your feedback is a great data point to have. the theory was that the typing would give folks time to digest what is gong on, but that's inevitably going to make others bored. Often times I fast forward the typing, but I seemed to speak a lot while typing in this one. Glad you learned something from it!

    • @dj-maxus
      @dj-maxus Рік тому +2

      @@codetothemoon As for me, your real-time typing really helps to digest all the information consciously, like, straight to the brain cortex. It feels like pair programming when you guide through the things and concepts being shown. At the same time, I can speed up your video if I need to

    • @houtamelocoding
      @houtamelocoding Рік тому +2

      I honestly the enjoy the typing sounds, they are quite satisfying

  • @pineappleexpress2307
    @pineappleexpress2307 Рік тому +1

    The