The Box Smart Pointer in Rust

  Рет қаралды 69,698

Let's Get Rusty

Let's Get Rusty

Күн бұрын

The ultimate Rust lang tutorial. Follow along as we go through the Rust lang book chapter by chapter.
📝Get the FREE Rust Cheat Sheet: letsgetrusty.com/cheatsheet
The Rust book: doc.rust-lang.org/stable/book/​​
Chapters:
0:00​ Intro
0:29 Pointers, References, and Smart Pointers
2:38 Using a Box to Store Data
4:43 Enabling Recursive Types with Boxes
11:53 Outro
#letsgetrusty​​ #rust​lang​ #tutorial

Пікірлер: 77
@letsgetrusty
@letsgetrusty 3 жыл бұрын
📝 Get your *FREE Rust cheat sheet* : www.letsgetrusty.com/cheatsheet
@long-live-linux
@long-live-linux Жыл бұрын
The following code works: #[derive(Debug)] enum List
@sagnikbhattacharya1202
@sagnikbhattacharya1202 3 жыл бұрын
Please cover RefCell :)
@letsgetrusty
@letsgetrusty 3 жыл бұрын
Coming up!
@GolangDojo
@GolangDojo 3 жыл бұрын
Golang beginners - Pointers are so hard to understand Rusty Bogdan - Regular pointers aren't cool enough
@plutonium_guy
@plutonium_guy 3 жыл бұрын
so true
@mindmaster064
@mindmaster064 2 жыл бұрын
If you ever had any problems in your code with dangling pointers you don't miss 'em. I'll stay happy with the little Box and be even happier I never have to deal with that mess. What you won't use in this is the List enum because linked lists are hot garbage and there is absolutely zero use case except for some kludge-y recursive algorithms. Using Box with Vec is however the best way to use it. We all have growable Vec's that we need to pass between bits of code by reference. I think linked list information really should be included in another topic specifically on recursion where it is most likely to be used, because for the rest of the programming you ever do you just won't care about it or use it.
@brianteague8031
@brianteague8031 2 жыл бұрын
Congrats! You are half way through the tutorial series! Keep up the momentum! Thanks for the great videos bogdan!
@prawnydagrate
@prawnydagrate 8 ай бұрын
this comment actually made me very happy, thanks!
@thingsiplay
@thingsiplay 3 жыл бұрын
You do a great job in explaining these things. Thank you for the videos.
@user-pe2qw4hz4n
@user-pe2qw4hz4n 2 жыл бұрын
A very clear explanation and a good example. Thanks for the video!
@dazealex
@dazealex Жыл бұрын
Didn't even want to learn Rust... But, the presentation and bite sized nature is easily digestable!
@vjau75
@vjau75 2 жыл бұрын
That was well explained, thank you.
@jayleejw1801
@jayleejw1801 15 күн бұрын
THE RUST GANG!!
@jonxslays
@jonxslays 3 жыл бұрын
i have gotten a lot out of your videos thanks dude!!
@norbertskalski62
@norbertskalski62 Жыл бұрын
I know that you are calling this a "cons list" but this is just an old school linked list. Cons might be from lisp, but linked lists are language agnostic
@dagoberttrump9290
@dagoberttrump9290 2 ай бұрын
it's not an old school linked list. linked list consists of a accessory struct and nodes, whereas each node points to the next one. in a cons list, each list points to another or no list
@norbertskalski62
@norbertskalski62 2 ай бұрын
@@dagoberttrump9290 a cons list points to another cons list or no list. so exactly like a classical linked list... (obviously a node points at another node, but structurally another node is just the start of another linked list). i think its just semantics at this point.
@jonathanmoore5619
@jonathanmoore5619 3 жыл бұрын
Thank you.
@TheHelvetican
@TheHelvetican Жыл бұрын
Thanks for what your do.
@sang89vh
@sang89vh 2 жыл бұрын
thanks so much!
@ancientITguy
@ancientITguy 2 жыл бұрын
Amazingly good content!
@EbonySeraphim
@EbonySeraphim 2 жыл бұрын
Seems like you could also get away with using Option right? Is Option a smart pointer type as well since it can be None? EDIT: Nope. Option needs to know the size of T
@MK-fd3gz
@MK-fd3gz 2 жыл бұрын
Option perhaps.
@XFajk
@XFajk Жыл бұрын
Isnt that just a link list and if not what is the difference 🤨
@markstumbris7824
@markstumbris7824 2 жыл бұрын
Learning and enjoying your videos 👍 I think none would be the proper syntax here. No nils in Rust
@reinismuiznieks7478
@reinismuiznieks7478 3 жыл бұрын
Awesome! Keep it up! Hope you will soon switch to 2 videos per week :)
@thisistraightgarbage
@thisistraightgarbage Жыл бұрын
It doesn't change the point you were making about how the compiler calculates the size of recursively data structures, but the actual size of an enum is going to be... SIZE_OF_LARGEST + SIZE_OF_TAG, as enums are what would be called *tagged unions,* in other languages. I'm ignoring padding/alignment, here, cuz I don't actually know much about that wrt Rust
@tandex3414
@tandex3414 Жыл бұрын
more usefull use of Box is using traits, when you just store object as trait
@donateus6743
@donateus6743 3 жыл бұрын
Keep going bro
@kiddkai
@kiddkai 2 жыл бұрын
How to impl a iterator for this emum?
@sakuranooka
@sakuranooka 2 жыл бұрын
Why we need the use statement at 6:43? Assuming an enum is like a type, what does it mean "to bring a type into scope", and why isn't it already in scope right after being defined?
@dulanchampa
@dulanchampa 2 жыл бұрын
Here "to bring a type into scope" means bringing the variants of enums into main scope. i.e. you can write it like: "Variant" instead of "Enum::Variant"
@sakuranooka
@sakuranooka 2 жыл бұрын
@@dulanchampa Thanks!
@xad85
@xad85 3 жыл бұрын
I really liked your explanations. I just have a question about the recursive list structure. You mentioned at the end of the video that line 9 is not very readable. It got me thinking if there would be any other nicer way of making it more readable but using the same recursive data structure approach. Do you have any idea in mind? keep rolling the videos!! :)
@bebo3276
@bebo3276 2 жыл бұрын
Well you could define a little helper function like this: fn cons(i: i32, list: List) -> List { List::Cons(i, Box::new(list)) } and then construct the list like this: let list = cons(1, cons(2, cons(3, Nil)));
@alagaika8515
@alagaika8515 Жыл бұрын
You could also define a helper function that adds one layer, like: fn prepend(l: List, value: i32) -> List { Cons(value, Box::new(l)) } let mut l = Nil; l = prepend(l, 5); l = prepend(l, 7);
@DaviAreias
@DaviAreias Жыл бұрын
I found this part of the book confusing :(, in the book it doesn't show that rust knows list is of type List, but in your VScode we can see the type, but it's not clear how it was able to infer the type. Why it doesn't treat list as "Cons" for example?
@alagaika8515
@alagaika8515 Жыл бұрын
Doesn't an enum need additional memory to specify which of the variants is actually stored?
@Dan-yb1wy
@Dan-yb1wy Жыл бұрын
It doesn't always need extra space. For example, if you call std::mem::size_of::() it returns 8. The compiler uses null pointer optimization and uses 0 to represent the 'None' option and any other value to represent the 'Some' option so a tag field isn't needed. It can't do this with eg. Option because all values of u64 are valid, so the size is 16 bytes (8 bytes for u64, 1 byte for tag, and 7 bytes padding for alignment). It can do it for pointer-like types (eg. &T, &mut T, Box, function pointers) and numerical types where 0 isn't a valid representation, eg. core::num::NonZeroU64. size_of::() == 8 size_of::() == 16
@Nico-rl4bo
@Nico-rl4bo 2 жыл бұрын
7:20 getting flashbacks from functional programming pls put a trigger waring there xd
@redcrafterlppa303
@redcrafterlppa303 2 жыл бұрын
O wow I just realized that a rust enum is basically a union
@RenderingUser
@RenderingUser Жыл бұрын
What's a union?
@redcrafterlppa303
@redcrafterlppa303 Жыл бұрын
@@RenderingUser a datatype that only allocates space to hold one of its members. Example: union Foo { i32 x, i64 y, i128 z, } is 128 bits long The difference between rust enum and union is that at runtime the information which one is active is not available in a union and is often stored alongside in a separate field or manually kept track of by the developer.
@jobosan4855
@jobosan4855 2 жыл бұрын
What is the point of deallocating Box(5) when the program terminates??? Isn't the entire stack and heap automagically deallocated at program termination?
@minerscale
@minerscale Жыл бұрын
If you have a program which runs for a long time and has lots of allocations, this is called a memory leak. Over time the entire system memory gets taken up by data which isn't accessed by anyone until the system no longer has any memory to hand out which is very bad.
@sonicsplasher
@sonicsplasher 5 ай бұрын
How is this different from a linked list?
@hcn6708
@hcn6708 Ай бұрын
The Nil variant in my project is 4 bytes ☹
@Michael-en7ub
@Michael-en7ub 2 жыл бұрын
Interesting! But now I'm wondering: could a & reference be used instead of Box? What are the upsides to using Box in this example?
@someon3
@someon3 Жыл бұрын
Nope, you can't allocate new memory and save it on a reference, you need a box to do it
@lizzienovigot
@lizzienovigot Жыл бұрын
@@someon3 yeah, but why not? What is the reason?
@RenderingUser
@RenderingUser Жыл бұрын
​@@lizzienovigotbecause... That's... How it's made?
@flippert0
@flippert0 7 ай бұрын
@@lizzienovigot You cannot transfer ownership with a normal reference.
@lizzienovigot
@lizzienovigot 7 ай бұрын
@@flippert0 I know, but thats not exactly what I asked. As far as I understood the original comment "could a & reference be used instead of Box?", it referred to the Linked List example in the video, so the question is "could linked list be written in Rust using references, not Boxes". Its not immediately obvious that you need to keep ownership, so just brushing it off with "you cannot transfer ownership with a reference" does not answer the question. Maybe I dont need to transfer ownership. Maybe I do, but its not obvious.
@kuqmua755
@kuqmua755 3 жыл бұрын
But what if there are so many pointers and structures even on heap - what will be result of this situation? out of memory error? Panic? Process will be killed by os? What happens? And how set a limit for number of pointers and enums instances? For example if i want to set 100 limit and set it in "enum logic" or some structure what would wrap enum. Sorry for my English
@KohuGaly
@KohuGaly 3 жыл бұрын
If allocation fails, rust program just terminates with out of memory error. The program can't panic, because panic needs to drop all values and drops may allocate memory (which we don't have). To limit the number of items in the list, you need some struct that keeps track of the length, and you need the list to be a private field of the struct, so it can't be accessed by the user directly. The creation and modification of the list needs to happen through the methods of the struct, so it can enforce the maximum capacity with custom logic.
@alagaika8515
@alagaika8515 Жыл бұрын
@@KohuGaly Box also has a try_new that allows you to gracefully catch allocation errors
@letsgobrandon416
@letsgobrandon416 Жыл бұрын
Isn't a pointer to a small object, such as ints and chars, just as expensive as the object itself?
@thisistraightgarbage
@thisistraightgarbage Жыл бұрын
It is. In fact, on a 64 bit architecture, a pointer (8 bytes) is larger than an i32 (4 bytes)
@johndoex94
@johndoex94 Жыл бұрын
Stupid question, but why do your VSCode suggestions have a benzene molecule?
@RenderingUser
@RenderingUser Жыл бұрын
Tabnine I think It's an AI based tool
@sonicsplasher
@sonicsplasher 5 ай бұрын
Github copilot wasnt available 2 years ago. TabNine was a really good AI-based suggestion tool
@bitflogger
@bitflogger 2 жыл бұрын
This (and the book) bugged me because I wanted to print the list. let list = Cons(2, Box::new(Cons(3, Box::new(Nil)))); print!("["); let mut item = list; let mut first = true; loop { let y = match item { List::Cons(a, next) => { item = *next; a } List::Nil {} => { println!("]"); break; } }; if !first { print!(", "); } print!("{}", y); first = false; }
@bobbybob628
@bobbybob628 2 жыл бұрын
I don't really understand the cases of using smart pointer, particularly Boxes ... Even though the explanation of writing the code is clear.
@ChumX100
@ChumX100 2 жыл бұрын
As illustrated by the example in the video, Box is useful when the size of the data cannot be known at compile time, but a fixed size structure is required by the compiler (as in recursive structures). Now, you could use regular references in these scenarios as well, making Box redundant, but there is a key difference: Box owns the data it points to, while regular references do not. So with references, you would need to specify lifetime parameters to make sure that the reference is valid throughout your program. Box is convenient as it handles heap allocation and deallocation automatically based on variable scopes and as it implements the Deref trait, can be used as value directly.
@bobbybob628
@bobbybob628 2 жыл бұрын
@@ChumX100 Thanks man! I got it when i checked again
@RocketmanReal
@RocketmanReal 2 жыл бұрын
@@ChumX100 ​ that makes sense, but if using smart pointers is more convenient option, what are the downsides compared to lifetimes? Is it a good idea to just use smart pointers and forget about explicit lifetime annotations? Rust could use it internally, with some syntax sugar, and not bother users with lifetimes, but it doesn’t… I guess because smart pointers are real structs and require additional memory allocation?
@tossitossi8207
@tossitossi8207 Жыл бұрын
I always get this doubt are you saying "the rust programming language " or "the best programming language " ?
@aryansinha1818
@aryansinha1818 11 ай бұрын
4:43
@complicated2359
@complicated2359 Жыл бұрын
Not that great explanation because cargo check prmoted not only box, but also rc, so it wasnt clear why you didnt use rc instead.
@sadiqabubakar7185
@sadiqabubakar7185 2 ай бұрын
Anyone from the future still here
@giorgilagidze9020
@giorgilagidze9020 2 жыл бұрын
why do you keep copying/pasting examples from the book ? come up with your ones(better ones). To me, it seems like whatever book says, it's mentioned in these videos.
@brianteague8031
@brianteague8031 2 жыл бұрын
The title of the video series is "The Rust Lang Book", so he's basically going over whatever is in the book.
Smart Pointers in Rust - The Deref Trait
10:00
Let's Get Rusty
Рет қаралды 33 М.
Smart Pointers in Rust - Interior Mutability
17:04
Let's Get Rusty
Рет қаралды 41 М.
Я обещал подарить ему самокат!
01:00
Vlad Samokatchik
Рет қаралды 8 МЛН
Best KFC Homemade For My Son #cooking #shorts
00:58
BANKII
Рет қаралды 68 МЛН
All Rust string types explained
22:13
Let's Get Rusty
Рет қаралды 157 М.
Choose the Right Option
18:14
Logan Smith
Рет қаралды 68 М.
8 deadly mistakes beginner Rust developers make
14:14
Let's Get Rusty
Рет қаралды 161 М.
Async Rust Is A Bad Language | Prime Reacts
28:46
ThePrimeTime
Рет қаралды 91 М.
Rust Modules - Explained Like I'm 5
19:59
Let's Get Rusty
Рет қаралды 70 М.
You Should Really Know These Traits in Rust
18:36
Oliver Jumpertz
Рет қаралды 12 М.
Rust Functions Are Weird (But Be Glad)
19:52
Logan Smith
Рет қаралды 131 М.
Rust Powered Polymorphism ⚡️ With Traits
9:55
Code to the Moon
Рет қаралды 94 М.
Rust's Witchcraft
9:18
No Boilerplate
Рет қаралды 176 М.
Rust Data Modelling Without Classes
11:25
No Boilerplate
Рет қаралды 167 М.
Kumanda İle Bilgisayarı Yönetmek #shorts
0:29
Osman Kabadayı
Рет қаралды 2,3 МЛН
НЕ БЕРУ APPLE VISION PRO!
0:37
ТЕСЛЕР
Рет қаралды 375 М.
Частая ошибка геймеров? 😐 Dareu A710X
1:00
Вэйми
Рет қаралды 3,7 МЛН