CH 4. Understanding Ownership. Flashcards
What is the ownership model used for?
Its used as a way to manage memory.
What is the stack?
The stack is a fixed sized memory allocation that cannot grow or shrink during runtime. The stack also stores stack frames which stores function/variables and their size, the size is calculated at compile time. So variables must have a known size at compile time.
What is the heap?
The heap is a dynamic sized memory allocation that can change throughout runtime. Memory used in the heap have lifetimes which we can control to determine how long memory is used for and when to discard it.
Is is faster to allocate/retrieve data from the stack or the heap and why?
The stack is faster because this memory is known and has memory already allocated for it, whereas the heap will need to look for open space to allocate memory for. When retrieving data the heap will have to follow a pointer whereas the stack will have the memory needed.
What are the three core ownership rules for 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.
What is a move in Rust?
A move is when you try to copy a value which is stored on the heap, because rather than copy the value which would take up more memory, the values instead move in ownership for that value.
let x: i32 = 5;
let y: i32 = x; // Copy
// Remember String is stored dynamically
let s1: String = String::from(“Hello”);
let s2: String = s1; // Move
// This next line cant compile because s1 has been dropped from memory since
// its value moved in ownership to s2
println!(“{}, world!”, s1;
What determines if a functions passed in parameter values will be copied or moved?
If the passed in values are stored on the heap or on the stack.
Are returned values from a function moved or copied?
They are moved.
What is a reference?
A reference is a pointer that wont take ownership of a value when used. In rust a pointer is indicated by the & key.
Are references mutable?
Not by default, but they can be.
What is the scope of a reference?
From when it is first declared to when it is last used.
What is a dangling reference?
It is a reference that points to invalid data.
What are the two rules of references in Rust?
- At any given time, you can have either one mutable reference or any number of immutable references.
- References must always be valid.
What are slices?
References to a continuous sequence of elements within a collection.
Do slices take ownership of the data?
No