Rust Lifetimes Finally Explained!

Поделиться
HTML-код
  • Опубликовано: 6 июн 2024
  • The ultimate Rust lang tutorial. Follow along as we go through the Rust lang book chapter by chapter.
    📝 Get your *FREE Rust Cheat Sheet*: www.letsgetrusty.com/cheatsheet
    The Rust book: doc.rust-lang.org/stable/book/​
    0:00 Intro
    0:22 The Borrow Checker
    3:03 Generical Lifetime Annotations
    10:29 Thinking in Terms of Lifetimes
    12:25 Lifetime Annotations in Struct Definitions
    13:27 Lifetime Elision
    15:35 Lifetime Annotations in Method Definitions
    17:07 Static Lifetimes
    17:27 Putting it All Together
    18:33 Outro
    #letsgetrusty​ #rust​lang #tutorial
  • НаукаНаука

Комментарии • 223

  • @letsgetrusty
    @letsgetrusty  3 года назад +13

    📝 Get your *FREE Rust cheat sheet* : www.letsgetrusty.com/cheatsheet

  • @ChumX100
    @ChumX100 2 года назад +243

    I really like how Rust doesn't hide complexity from developers behind trade-offs, but rather offers helpful tools to manage complexity as well as sensible defaults.

    • @HermanWillems
      @HermanWillems 2 года назад +21

      This transparancy i like. I dislike magical garbage collectors and other stuff. This is why rust is so great.

    • @kevinmcfarlane2752
      @kevinmcfarlane2752 2 года назад +16

      There are arguments for both, depending on your application domain. There is never a one size fits all.

    • @zacharybrown3486
      @zacharybrown3486 Год назад

      biggest draw for me as well

    • @Tsundaere
      @Tsundaere Месяц назад

      Well put. I'm still wrangling my brain around some of the stuff but slowly it's getting there and with each step you realise how awesome it really is.

  • @thingsiplay
    @thingsiplay 3 года назад +210

    I had trouble understanding the lifetime annotations system, until this video. The key information I needed was "It does not change the lifetime, but specifies relationships" explanation.
    Your videos and explanation are clear and easy to follow. Can't wait to see more material. Thanks for going through this and doing all the work.

  •  3 года назад +308

    Frustrated beginner Rust programmer: "Just let me write bad code!!"
    The Rust compiler: No. Here's some super helpful tips instead.

    • @joelimbergamo639
      @joelimbergamo639 2 года назад +36

      That's exactly how I feel writing rust, I want to write code that I know it's wrong but I want to only try it and rust forces me to write good code, it's a love hate relationship 😂

    • @garlicat878
      @garlicat878 2 года назад +23

      Exactly. We should make a meme like:
      Me after learning other languages for hours: Wow Let's make a app/game/website.
      Me after learning Rust for weeks: Why doesn't it compile? What lifetime annotation should I put here? Should I borrow that thing?

    • @HermanWillems
      @HermanWillems 2 года назад +15

      I love Rust is forcing me to do the right thing. For example it forces me to handle the options, use the match. But also with using the match statement it forces me to use all posibilities. No null. I love it doesn't have null. (Well in safe space though) but i like how its the default. The defaults are chosen perfectly.

    • @vorrnth8734
      @vorrnth8734 2 года назад +6

      @@joelimbergamo639 Having had to debug muuuch bad code I really love this behaviour. Dangling pointers can be a real pita.

    • @conradmbugua9098
      @conradmbugua9098 2 года назад

      🤣🤣🔥

  • @Familia_nepal_nepal_do_mal12
    @Familia_nepal_nepal_do_mal12 11 месяцев назад +5

    As a Java/Node/python programmer and learning Rust I never understood lifetimes in Rust, you`re the first to make this `click` in my brain. Thank you.

  • @richasha670
    @richasha670 3 года назад +60

    I totally understand lifetime by your video! Thank you so much as a Rust beginner, you made me understand Rust Book 200%!

    • @kevinmcfarlane2752
      @kevinmcfarlane2752 2 года назад +5

      Yeah he complements the book nicely. I find with technical topics that I need a combination of written material, presentations like this and experimentation/practice to get the richest understanding.

  • @fixpoint
    @fixpoint 2 года назад +4

    Thank you for explaining lifetimes in a clear and easy to understand manner. I just discovered your series and can’t wait to go through the rest of them! Thank you for the time and effort you have put in to produce these.

  • @embedded_software
    @embedded_software Год назад +1

    I was watching this video on the treadmill, and I was enjoying it so much that I actually worked out longer than I was planning without even realizing it until the video was over! Thanks, Bogdan!

  • @chsblue2
    @chsblue2 2 года назад +8

    Perfect explanation. You just gave me that little extra information that I was missing to finally get it into my head. Thx man! 👏🏻

  • @bertolucci1985
    @bertolucci1985 2 года назад +16

    Thanks for taking the time to produce these videos mate. Learning Rust concepts alone isn’t easy. I appreciate it.

  • @sulfurasmr6365
    @sulfurasmr6365 11 месяцев назад

    this channel has been hugely helpful for me trying to learn rust, especially since I've never heard of a language doing 'borrowing' before. thank you so much!

  • @kumatmebrah9044
    @kumatmebrah9044 Год назад +1

    Watching this after going through the chapter helps drive the point home. I'm glad I found this.

  • @TAT4guitar
    @TAT4guitar Год назад

    I have been learning Rust from youtube and Rust by Example, and your videos always do the best job when it comes to tricky concepts such as ownership and lifestime. Thanks a lot!

  • @SansDev
    @SansDev 4 месяца назад

    This series is outstanding tbh, thank you for your hard work. Understanding each of Rust's features makes me love it so much more!

  • @meka4996
    @meka4996 2 года назад +1

    Your explanation is super clear! I know lifetime now! Thank you

  • @stanislavstudzinskyi2347
    @stanislavstudzinskyi2347 Год назад

    Outstanding quality. Thank you so much for your labor!

  • @oliverhunter1847
    @oliverhunter1847 Год назад

    Hands down, the best explanation of lifetimes I've ever seen

  • @absarrahman9177
    @absarrahman9177 6 месяцев назад

    THIS IS BY FAR THE BEST EXPLANATION. Keep it up man

  • @oyunovacom
    @oyunovacom 2 года назад +1

    Bogdan, this video is even clear for me as a code illiterate! Thank you for this and PLEASEEEE keep your lectures this minimal! Cheers!

  • @hhhuhhh5692
    @hhhuhhh5692 6 месяцев назад

    Thank you so much! This video and the others in this playlist really helps me understand Rust better! ❤

  • @faanross
    @faanross 2 месяца назад

    your videos are just so incredible man, extremely grateful for these beautifully articulated insights you put out

  • @web3987
    @web3987 9 месяцев назад

    Thank you for such a comprehensive lifetimes lesson. The learnings from this video will last a lifetime.

  • @LagDaemonProgramming
    @LagDaemonProgramming 2 года назад

    Your explanations of these topics are concise, complete, detailed and you move right along with them. Outstanding job, all of your videos make these ideas very clear. I tip my hat to you sir! :)

  • @twentyeightO1
    @twentyeightO1 Год назад +1

    This channel is a blessing!

  • @gzoechi
    @gzoechi Год назад +1

    Good explanation of a bunch of things I had a really hard time understanding from the Rust book, when I started learning Rust. This could have spared me a lot of pain 😬

  • @GolangDojo
    @GolangDojo 3 года назад +12

    Just let me live life dangerously

    • @ajesh-mishra
      @ajesh-mishra 3 года назад +4

      Rust Compiler: Nope! Not on my watch ⌚ safety first 🎈

    • @vorrnth8734
      @vorrnth8734 2 года назад +1

      Then do C or assembler.

  • @user-dg9cr6wu9i
    @user-dg9cr6wu9i 2 года назад +1

    Awesome! These examples are very clear for rust lifetime.

  • @NeotenicApe
    @NeotenicApe 3 года назад +2

    Your videos are amazing! Thank you so much ❤️

  • @andriesvanwyk3226
    @andriesvanwyk3226 2 года назад +1

    Very clear explanation! Thank you!

  • @tobi9648
    @tobi9648 4 месяца назад

    wow, I saw these 'a-ticks and couldnt find a good/easy explanation for it. You just explained it so easy and perfect. Thanks!!

  • @PoetNoPoems
    @PoetNoPoems 3 года назад +1

    These videos have been fantastic, thank you

  • @joehsiao6224
    @joehsiao6224 Год назад +1

    Resolving a longtime mystery in my mind feels so good.
    I'd spam the like button if I could.

  • @MameMedouneDiopXpert
    @MameMedouneDiopXpert Год назад

    Lifetimes are clear now! Thank's a lot Bogdan

  • @2002budokan
    @2002budokan 2 года назад

    You know what? This is currently the best video resource to learn Rust. Thank you Bogdan.

  • @dulanjala
    @dulanjala Год назад

    this is a nice little tutorial with so much value. Thanks!

  • @klaymen0
    @klaymen0 2 года назад +6

    Thanks for the video series, it's a great addition to the book as it gives a different perspective to a lot of things. One thing I wonder about lifetimes (and I'm learning, so maybe I did not grasp the concept fully yet): It seems to me that assigning the same lifetime 'a to ALL parameters of a function plus all returned parameters is the most restrictive way possible in terms of lifetimes. If an actual use of a function fulfills these "strictest" rule, why is it actually required to write these lifetimes out when defining it? I think, in the longest-string example, no different lifetime declaration than this most restrictive one is even possible - if you try it, a bug occurs where you try to return the "other" parameter. I understand it's probably a complex problem for the compiler, maybe NP-complete, to find the optimal setting, but in cases where the most restrictive remaining one works, why not defaulting to this? One possible explanation (and maybe this is the reason) is when you write a library that exports functions, so the compiler does not know how it is actually used, so lifetime declarations must be exported as well. But this would not apply for private functions. Another way to make it easier would be to add a mode (maybe compiler flag) to automatically fill up lacking lifetimes with the most restrictive setting still possible? Or what also might be interesting (maybe this exists) were external tools, a bit like lint, or optimally included in an IDE, that could auto-suggest lifetimes?

  • @abhinavchavali1443
    @abhinavchavali1443 3 года назад +1

    This is the best youtube video I have ever watched.

  • @Tanger68
    @Tanger68 11 месяцев назад

    You explain this very succinctly, thank you very much! In my mind, lifetimes are almost intuitive once you think about it. I think I just double guess myself because I expect it to be more complex than it is!

  • @AndresFH7233
    @AndresFH7233 2 года назад

    Dude great explanation, I finally got the concept!

  • @dimiutube
    @dimiutube 6 месяцев назад

    Awesome! Good explanation of the lifetime concept. I'm looking forward to deal with different lifetimes for variables and convince the compiler that all I'm doing is well planned 🙈 Thank you very much!!

  • @murugarajuperumalla5508
    @murugarajuperumalla5508 2 года назад

    Super, this video is enough to understand lifetime, thanks a lot ❤️❤️

  • @dmitriidemenev5258
    @dmitriidemenev5258 Год назад +6

    Hi, Bogdan! I would be really cool to see a video about structs where some fields reference others. More precisely, why it is or is not bad and what are the alternatives.

    • @zemja
      @zemja Год назад

      You cannot do this in Rust.

  • @Timjstewart
    @Timjstewart 8 месяцев назад

    So thorough and interesting! Thanks!

  • @gauravpoudel7288
    @gauravpoudel7288 2 года назад

    AWESOME EXPLANATION.!! thANKS SO MUCH!

  • @chlbri
    @chlbri Год назад

    You explain very well some difficult notions.

  • @tourdesource
    @tourdesource 2 года назад

    Clear as day. Thank you!

  • @b_mathemagical
    @b_mathemagical 5 месяцев назад

    I rarely comment on videos, but you did a great job with this. Thanks for sharing!

  • @NoNameEntered
    @NoNameEntered Год назад

    Great video and examples! Thank you!

  • @shhhhhhKoiHai
    @shhhhhhKoiHai 3 года назад

    This is great explanation. Love it. Thanks.

  • @lee45283
    @lee45283 3 года назад +2

    Great video, thanks for the content!

  • @aaronzolotor430
    @aaronzolotor430 Год назад

    This was amazingly helpful!

  • @madhank93
    @madhank93 3 года назад +1

    Very nicely done. Thank you 🙏

  • @johnegan2484
    @johnegan2484 2 года назад +1

    You state at ~13:15 that the lifetime annotation is saying our struct cannot outlive the reference passed into part:first sentence so if we try to use our variable i (agreed) which is an instance of our struct after part:first sentence has gone out of scope we would get an error.
    However, would note that the annotation means that an instance of ImportantExcerpt cannot outlive the reference it holds in its part:first_sentence field and in that regard the reference in the ImportantExcerpt instance is valid, the owning variable novel does not go out of scope prior to ImportantExcerpt going out of scope.

  • @Lexikon00
    @Lexikon00 3 года назад +17

    I just wanted to address something that a lot of new rust programmers get wrong, and you also did explain it wrongly. At least it's rarely the case someone wants to do this.
    I'm going to copy the code you used for the illustration:
    struct ImportantExcerpt ImportantExcerpt

    • @letsgetrusty
      @letsgetrusty  3 года назад +10

      Hey Alexander, thank you for the correction and taking the time to write this out.

    • @johnegan2484
      @johnegan2484 2 года назад +2

      To clarify, because there are two input lifetimes both &self and announcement:&str are given their own lifetimes.(Rule #1) Because one of the parameters is &self, the return type gets the lifetime of &self. (Rule #3)

  • @kiddkai
    @kiddkai Год назад

    Great video, help me understand the lifetime annotation!

  • @michaelkastner3611
    @michaelkastner3611 Год назад

    Again, another great episode.

  • @tak68tak
    @tak68tak 2 года назад

    So clear. Thanks.

  • @RoamingAdhocrat
    @RoamingAdhocrat 11 месяцев назад

    and you may ask yourself, why did I struggle with this?
    Thanks for the explanation. I'd found lifetimes confusing up to now, but the way you demonstrated it, it's quite straightforward!

  • @kch9001
    @kch9001 Месяц назад

    Best lifetime explanation on youtube

  • @JhonatanMorais
    @JhonatanMorais 2 года назад

    GREAT video. thank you so much.

  • @dadestor
    @dadestor Год назад

    Great video and explanation, thanks

  • @shaneosbourne8640
    @shaneosbourne8640 3 года назад +1

    Thanks for the great content

  • @kg3217
    @kg3217 2 года назад

    Thank you : )
    Thanks again
    Thanks a lot
    Thank you for explaining it so well 🙏

  • @jacques-dev
    @jacques-dev Год назад

    Wowie. Thanks Bogdan!

  • @strawz1988
    @strawz1988 Год назад +1

    Thanks for such a neat explanation. Just a request the audio is little low

  • @platput
    @platput 3 года назад

    Thanks for this video.

  • @hungnguyenthanh2800
    @hungnguyenthanh2800 Год назад

    Very nice explanination!!!!

  • @berliangigihprakoso6948
    @berliangigihprakoso6948 3 года назад +1

    very good man, your videos is easy for beginer like me.❤👍

  • @darshanv1748
    @darshanv1748 2 года назад +4

    at 16:50 if we return announcement from the function , then according to lifetime ellisions it'll be assigned lifetime of self, but don't you think that it might be wrong in some cases

    • @proloycodes
      @proloycodes 2 года назад +1

      yes it will be wrong. im sure it will give some "announcement does not live long enough." type of error

  • @funkdefied1
    @funkdefied1 6 месяцев назад

    Thank you!

  • @vijaysinghbisht3016
    @vijaysinghbisht3016 2 года назад

    Thank you very much.. Explained very nicely..
    Can you do a day event?

  • @elonmax404
    @elonmax404 2 года назад

    Thank you very much. Subbed.

  • @mortymacs
    @mortymacs Год назад

    Awesome! thanks a lot!

  • @OggerFN
    @OggerFN 2 года назад

    Great video. Only thing I miss here would be showing how different lifetimes interact with each other inside the fn scope to further illustrate the concept.

  • @mhhmm__
    @mhhmm__ Год назад

    awesome !!! thank you

  • @kvasco-iu8nq
    @kvasco-iu8nq 2 года назад

    Superb! really good explanation, got some small pieces that help me to get my head around this lifetime thingy.
    in the fn longest example, m 11:02 it works if we use string slices instead of Strings, my guess is because these implement the copy trait ? hence the values are moved so the reference to result is valid at the end ?

  • @uuaae
    @uuaae 3 месяца назад

    You're a great teacher. Thank you for making this video! Do you know why lifetimes in Rust are rarely given descriptive names? Almost every example I find uses single-letter names like "a".

  • @thecount25
    @thecount25 2 года назад

    Thanks that was useful

  • @bjugdbjk
    @bjugdbjk 2 года назад

    U r LEGEND man !!

  • @patrickstival6179
    @patrickstival6179 2 года назад

    nice. I like the examples

  • @sharifulislam-pd3sj
    @sharifulislam-pd3sj 2 года назад

    {
    Cool man! It's a great explanation.
    }

  • @MattJoinerPwns
    @MattJoinerPwns Год назад

    Amazing videos

  • @RealShabana
    @RealShabana Год назад

    Good explaination

  • @marinhobrandao
    @marinhobrandao 3 месяца назад

    I loved to know you like The Wheel of Time as well :D

  • @user-ko5yr9mo6d
    @user-ko5yr9mo6d 3 года назад +2

    намного понятнее чем в книжках. Спасибо)

  • @sahilverma4077
    @sahilverma4077 3 года назад +5

    Damn, we have a lot of restrictions, but I wish if I get through all these problems I will have a safer, low level, and fast code.
    Btw, I recently saw in google news that google is rewriting some part of android with Rust, wish more companies start adopting it.

    • @letsgetrusty
      @letsgetrusty  3 года назад +4

      It's good to catch the wave early :)

    • @ajesh-mishra
      @ajesh-mishra 3 года назад +5

      Also the new modules in Linux Kernel may be written in Rust and that would be big!

  • @oussamasethoum2755
    @oussamasethoum2755 Год назад +1

    If the block doesn't end until line 230 but the variable is not used after line 100, does rust deallocate the variable in line 101 or until the block ends?
    what is the case for the garbage collector?

  • @teachforyou6489
    @teachforyou6489 2 года назад

    Superb

  • @MikeM8891
    @MikeM8891 Год назад

    Is it possible to make recursive data types like tree nodes using references and lifetimes? Or do you need to use boxes? Boxes are supposed to allocate space on the heap but not all recursive data structures need the heap and should be able to be implemented entirely on the stack.

  • @unduloid
    @unduloid 7 месяцев назад

    So when would you use mixed lifetimes?

  • @williamschukwuebuka7907
    @williamschukwuebuka7907 Год назад

    What extension is that, that allows you see the types?

  • @jamesbarrow
    @jamesbarrow Год назад

    Smashed the like button. Didn't smash subscribe, already done that before ;)

  • @vitomadio
    @vitomadio 2 года назад

    Hey Bogdan, haw can I have both, rust-analyzer and RLS working at the same time on vscode? I read that rust-analyzer is the way to go but RLS seems very usefull to my. By the way great work with this channel man, keep going!

    • @letsgetrusty
      @letsgetrusty  2 года назад +1

      As far as I know you can’t use both at the same time. Why not just use rust-analyzer? What specific features do you need from RLS?

  • @gaelanm3920
    @gaelanm3920 2 года назад +1

    Let's start out by talking about ding-a-ling references.
    In all seriousness, great video.

  • @Jordan4Ibanez
    @Jordan4Ibanez 2 года назад

    I wish I could like this video more than once

  • @rahatsshowcase8614
    @rahatsshowcase8614 Месяц назад

    You explained really well! and after your explanation I was like is there any single case even where i will need 2 lifetime annotations like 'a and 'b to express my logic! because i think i could do my lifetime annotations for any function or struct just by using 'a only!
    because if u look deeply for functions it's just annotating all your parameters with 'a which have the possible to be returned from your function and return 'a on the other hand for struct as the struct will become invalid if a single property containing a ref becomes invalid which means we can always pass a single lifetime through the whole struct?
    because i have tried 5-10 examples and all are working with a single annotation perfectly as expected! so let me know your opinion regarding this!

  • @Scramblejams
    @Scramblejams 8 месяцев назад

    I believe this could use an update now that the non-lexical lifetime analyzer has been updated, correct? For example, I do not get an error with rust 1.72.1 on the code sample at 13:00.

  • @AlanDarkworld
    @AlanDarkworld Год назад +6

    Whoever decided to use single quotes in a non-pairwise fashion in the Rust syntax just wants to see the world burn.

  • @midwestmetro6361
    @midwestmetro6361 Год назад

    what's the name of the background music ? its relaxing

  • @thebsv
    @thebsv 3 месяца назад

    Have a small question about the last example, what is the lifetime of the variable ann which has a generic type T? Why wasn't it explicitly mentioned, like the other input parameters? Would 'ann' also have the same lifetime as x and y, meaning 'a?