Understanding Ownership Flashcards
How does Rust handle memory management?
Through a system of ownership with a set of rules that the compiler checks at compile time. None of the ownership features slow down your program while it’s running.
Why is pushing to the Stack faster than allocating to the Heap?
On the Stack, the OS does not have to search for the data. Allocating space on the heap requires more work, because the OS must first find a big enough space to hold the data and then perform bookkeeping to prepare for the next allocation.
What are some problems that ownership addresses?
- 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.
What are the three ownership rules in Rust?
- Each value in Rust has a variable that’s called its owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
When does memory become free?
When a variable that owns it goes out of scope.
When a variable goes out of scope, what special function is called by Rust?
drop, it is called automatically at a closing curly brace (Resource Acquisition Is Initialization (RAII)).
What is a move in Rust?
Transferring ownership of resources from one reference to another and invalidating the first reference.
What does the clone method do?
Performs a deep copy of a variable and value from Stack and Heap.
How is the Copy trait used?
Annotates types that are stored entirely on the Stack. If a type is annotated with Copy, an older variable is still usable after assignment.
What is the pattern the value of a variable follows everytime?
Assigning the value to another variable moves it.
When will a value be cleaned up by Drop?
When a variable that includes data on the heap goes out of scope, unless the value has been moved to be owned by another variable.
What does the & represent?
A reference.
What does a reference do?
Allow reference to some value without taking ownership of it.
What is borrowing in Rust?
Having references as function parameters. When an function is passed a reference to a value.
Are references mutable by default?
No.