The Box Smart Pointer in Rust

  Рет қаралды 76,967

Let's Get Rusty

Let's Get Rusty

Күн бұрын

Пікірлер: 82
@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
@brianteague8031
@brianteague8031 2 жыл бұрын
Congrats! You are half way through the tutorial series! Keep up the momentum! Thanks for the great videos bogdan!
@prawnydagrate
@prawnydagrate Жыл бұрын
this comment actually made me very happy, thanks!
@sagnikbhattacharya1202
@sagnikbhattacharya1202 3 жыл бұрын
Please cover RefCell :)
@letsgetrusty
@letsgetrusty 3 жыл бұрын
Coming up!
@thingsiplay
@thingsiplay 3 жыл бұрын
You do a great job in explaining these things. Thank you for the videos.
@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 3 жыл бұрын
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.
@gabiold
@gabiold Ай бұрын
@@mindmaster064Linked lists are very useful when eg. you have a stream of incoming unordered data, and want to order it on the fly. Or want to filter the list by permanently deleting items. With linked list, it is more performant to insert or delete in arbitrary locations than with vectors. Even when you store only pointers to the actual data chunks in the vector, you’ll still have to move around the pointers to keep it in order. If you have 2k items, once in a while, it might not matter much, but if you have 2G, then probably it’ll do. Or even just 2k items on a microcontroller would be a tad to slow for my taste. Although I am yet to come across a microcontroller task where I have to sort datasets with hard-RT requirements... 🤷🏻‍♀️
@dazealex
@dazealex 2 жыл бұрын
Didn't even want to learn Rust... But, the presentation and bite sized nature is easily digestable!
@sakuranooka
@sakuranooka 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
@@dulanchampa Thanks!
@babajagaisyou
@babajagaisyou Жыл бұрын
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 8 ай бұрын
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
@babajagaisyou
@babajagaisyou 8 ай бұрын
@@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.
@chudchadanstud
@chudchadanstud 3 ай бұрын
​@@dagoberttrump9290So a linked list? You don't need to wrap a node pointing to another node in a struct to call it a linked list.
@TheHelvetican
@TheHelvetican Жыл бұрын
Thanks for what your do.
@高主任-g6j
@高主任-g6j 3 жыл бұрын
A very clear explanation and a good example. Thanks for the video!
@jonxslays
@jonxslays 3 жыл бұрын
i have gotten a lot out of your videos thanks dude!!
@EbonySeraphim
@EbonySeraphim 3 жыл бұрын
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.
@vjau75
@vjau75 2 жыл бұрын
That was well explained, thank you.
@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 2 жыл бұрын
Nope, you can't allocate new memory and save it on a reference, you need a box to do it
@lizzienovigot
@lizzienovigot 2 жыл бұрын
@@someon3 yeah, but why not? What is the reason?
@RenderingUser
@RenderingUser Жыл бұрын
​@@lizzienovigotbecause... That's... How it's made?
@flippert0
@flippert0 Жыл бұрын
@@lizzienovigot You cannot transfer ownership with a normal reference.
@lizzienovigot
@lizzienovigot Жыл бұрын
@@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.
@XFajk
@XFajk Жыл бұрын
Isnt that just a link list and if not what is the difference 🤨
@alagaika8515
@alagaika8515 2 жыл бұрын
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
@sang89vh
@sang89vh 3 жыл бұрын
thanks so much!
@jonathanmoore5619
@jonathanmoore5619 3 жыл бұрын
Thank you.
@aryansinha1818
@aryansinha1818 Жыл бұрын
4:43
@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 11 ай бұрын
Github copilot wasnt available 2 years ago. TabNine was a really good AI-based suggestion tool
@Comdevsunion
@Comdevsunion 3 жыл бұрын
Learning and enjoying your videos 👍 I think none would be the proper syntax here. No nils in Rust
@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 2 жыл бұрын
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.
@1234fewgfwe
@1234fewgfwe 6 ай бұрын
THE RUST GANG!!
@ancientITguy
@ancientITguy 3 жыл бұрын
Amazingly good content!
@DaviAreias
@DaviAreias 2 жыл бұрын
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?
@kiddkai
@kiddkai 2 жыл бұрын
How to impl a iterator for this emum?
@Nico-rl4bo
@Nico-rl4bo 3 жыл бұрын
7:20 getting flashbacks from functional programming pls put a trigger waring there xd
@tandex3414
@tandex3414 2 жыл бұрын
more usefull use of Box is using traits, when you just store object as trait
@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 3 жыл бұрын
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 2 жыл бұрын
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);
@letsgobrandon416
@letsgobrandon416 2 жыл бұрын
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)
@reinismu
@reinismu 3 жыл бұрын
Awesome! Keep it up! Hope you will soon switch to 2 videos per week :)
@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.
@hcn6708
@hcn6708 7 ай бұрын
The Nil variant in my project is 4 bytes ☹
@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 2 жыл бұрын
@@KohuGaly Box also has a try_new that allows you to gracefully catch allocation errors
@sonicsplasher
@sonicsplasher 11 ай бұрын
How is this different from a linked list?
@chudchadanstud
@chudchadanstud 3 ай бұрын
It's not. It's just rust being rust. Sometimes the book is frustrating to read because of indirection like this. 90% of the examples used are not applicable to anything.
@bobbybob628
@bobbybob628 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
@@ChumX100 Thanks man! I got it when i checked again
@Rktmn
@Rktmn 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 2 жыл бұрын
I always get this doubt are you saying "the rust programming language " or "the best programming language " ?
@donateus6743
@donateus6743 3 жыл бұрын
Keep going bro
@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; }
@tech3425
@tech3425 4 ай бұрын
kewl
@sadiqabubakar7185
@sadiqabubakar7185 7 ай бұрын
Anyone from the future still here
@complicated2359
@complicated2359 2 жыл бұрын
Not that great explanation because cargo check prmoted not only box, but also rc, so it wasnt clear why you didnt use rc instead.
@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:01
Let's Get Rusty
Рет қаралды 37 М.
8 deadly mistakes beginner Rust developers make
14:14
Let's Get Rusty
Рет қаралды 179 М.
Vampire SUCKS Human Energy 🧛🏻‍♂️🪫 (ft. @StevenHe )
0:34
Alan Chikin Chow
Рет қаралды 138 МЛН
I'VE MADE A CUTE FLYING LOLLIPOP FOR MY KID #SHORTS
0:48
A Plus School
Рет қаралды 20 МЛН
OCCUPIED #shortssprintbrasil
0:37
Natan por Aí
Рет қаралды 131 МЛН
Rust's Alien Data Types 👽 Box, Rc, Arc
11:54
Code to the Moon
Рет қаралды 156 М.
Projects Every Programmer Should Try
16:58
ThePrimeTime
Рет қаралды 551 М.
All Rust string types explained
22:13
Let's Get Rusty
Рет қаралды 195 М.
Rust vs Zig vs Go Performance
7:10
Anton Putra
Рет қаралды 63 М.
7 Outside The Box Puzzles
12:16
MindYourDecisions
Рет қаралды 512 М.
Smart Pointers in Rust - Reference Counting
8:41
Let's Get Rusty
Рет қаралды 27 М.
Rust Functions Are Weird (But Be Glad)
19:52
Logan Smith
Рет қаралды 149 М.
Dear Game Developers, Stop Messing This Up!
22:19
Jonas Tyroller
Рет қаралды 791 М.
The Dark Side of .reserve()
18:50
Logan Smith
Рет қаралды 163 М.
Python laid waste to my C++!
17:18
Sheafification of G
Рет қаралды 193 М.
Vampire SUCKS Human Energy 🧛🏻‍♂️🪫 (ft. @StevenHe )
0:34
Alan Chikin Chow
Рет қаралды 138 МЛН