Smart Pointers in Rust
# Smart Pointers
Pointers -> an arrow to a value that’s somewhere else
Smart pointer -> pointers with additional features and metadata
|
|
Box is a smart pointer.
|
|
now 5 is stored on the head instead of the stack
what remains on the stack is a pointer to the heap data
b is still on the stack and it -> to the 5 on the heap
Impliments deref (dereference)
|
|
the reason this works is because pointers stay the same, so it’s a fixed size. This allows for dynamic sizes of things.
Option type tells rust a value can either be something or nothing
|
|
this implements null
singly linked list implimentation
|
|
# Doubly Linked List
Same of singly, but they also have a previous pointer
This doesn’t work!!!
|
|
this doesn’t work because of the rules of ownership. Each value has an owner and can only have one owner at a time.
# Shared Ownership
multiple owners??
another smart pointer
Rc<T>
short for reference counting. adds an additional feature of reference counting.
Imagine
Rc<T>
as a TV in a family room. When one person enters to watch TV, they turn it on. Others can come into the room and watch the TV. When the last person leaves the room, they turn off the TV because it’s no longer being used. If someone turns off the TV while others are still watching it, there would be uproar from the remaining TV watchers!
|
|
how it works
|
|
instead of box we will now use Rc
|
|
You don’t need to manually clear memory when any pointer goes out of scope
the above works except for one problem.
At any given time you can have either one mutable reference or any number of immutable reference, but not at the same time!
|
|
# Another Smart pointer!
RefCell<T>
Just like the compile-time borrowing rules,
RefCell<T>
lets us have many immutable borrows or one mutable borrow at any point in time.
What’s the difference with other borrows?
RefCell<T>
keeps track of how many immutable and mutable borrows we have!
If we are caught trying to break the rules it will instead panic at runtime instead of not compile.
with doubly linked list we need mutable pointers.
|
|
now this works!
This can be better though!