Rust: Store Data on the Heap with Box

preview_player
Показать описание
#rust #smart #box

! At 1:08, I said "Defer Trait", but I actually mean "Deref Trait"

Box is a straightforward example of one Smart Pointer in Rust. Box allows you to store data on the heap instead of the stack. Instead of passing around your data, and copying it’s total memory on the stack, you can use a Box to store the data and avoid the memory copies on the stack and defer to pointer copies on the stack. This is the single responsibility of the Box.

Box is a smart pointer because it implements the `Defer trait` which allows the `T` to be treated like references.

If you are unfamiliar with the concept of stack vs. heap, please refer to The Rust Programming Book chapter 4.

0:00 intro
2:05 Using Box to Store Data on the Heap
3:11 Enabling Recursive Types with Boxes
5:55 Computing the Size of a Non-Recursive Type
8:10 Using Box to Get a Recursive Type with a Known Size

Links

Learn more about traits

Box documentation
Рекомендации по теме
Комментарии
Автор

When reaching Box lesson I got epiphany that String is just Box::new("foo"). While not being exactly correct (String object is more feature rich than slice) it helped me to understand why compiler is not complaining about struct size when I define "Struct{ x: String }". Somehow suddenly this heap/stack concept "clicked" in my mind.

bbkr
Автор

I have checked. the Box did not implement Defer, it's trait Deref that you mean.

MohammadRajablooloverajabloo
Автор

is it possible to use `.into()` instead of the new constructor? Feels like that would make it look more intuitive.

yankee-in-london
Автор

oh boi i cant wait to see what this new trait "Defer" does
deref_move want

hezuikn