Ownership Flashcards
How does the stack store values?
In the order it gets them and removes the values in the opposite order.
Why is the stack fast?
It never has to search for it because it is always at the top. The data on the stck must also take up a known fixed size.
What data is suitable to be stored on the heap?
Data with a size unknown at compile time or a size that might change.
Is pushing data on the stack considered allocating?
No
Why is accessing data on the heap slower than on the stack?
Because you have to follow a pointer to get to the location.
When you call a function, the values passed into the function (including pointers to data on the heap) and the functions local variables get pushed onto the ____.
Stack
What does ownership address?
- Keeping track of what parts of code are using what data on the heap
- Minimizing the amount of duplicate data on the heap
- Cleaning up unused data on the heap so you don’t run out of space
Why does the concept of ownership exist?
To manage heap data.
What are the three rules of ownership in rust?
- Each value in rust has a variable that’s called its owner.
- There can be only one owner at a time.
- When the owner goes out of scope, the value will be dropped.
What is the scope of an item?
A scope is a range within a program for which an item is valid.
Why are string literals fast and efficient?
The text is hard coded directly into the executable.
Since rust doesn’t use a garbage collector, how does it keep track and clean up memory?
Memory is automatically returned once the variable that owns it goes out of scope.
What is the name of the function that is called when a variable goes out of scope?
Drop
How is a String stored on the stack?
Ptr |*
Len |
Capacity|
If s1 and s2 both point to the same content on the heap, what happens when both s1 and s2 go out of scope? Is this allowed in rust?
They will both try to free the same memory. This is known as double free error. Rust will invalidate the first variable when the second is assigned to it. This is called a move (similar to a shallow copy).