Ownership in Rust
# Ownership
this is what sets rust apart from other systems languages
! Each value has an owner
Only one owner per value, ( there may be borrowers )
when value goes out of scope it gets dropped.
|
|
this will throw a compiler error
|
|
This is because of memory stuff
Stack | Heap |
---|---|
In order | Unordered |
Fixed-size | Variable-size |
LIFO | Unordered |
Fast | Slow |
What does this have to do with a value being moved?
|
|
Stack | Heap |
---|---|
ptr-> | a |
len=3 | b |
capacity=3 | c |
when values go out of scope it just considers them uninitialized even though they are technically still on the stack
! More than a shallow copy -> it’s a MOVE
lets copy a value with clone method
Clone copies the stack and heap data and adjusts the copies pointer to point to the correct heap data. in other languages this might be called a deep copy
|
|
Rust reserves the copy term for when ONLY stack data is being copied
When a value is dropped
- the destructor (if there is one) is immediately run
- Free Heap (immediately)
- Stack is Immediately popped
that means NO leaks, or dangling pointers
Example of this
|
|
s1 is moved so it wouldn’t be usable outside do_stuff anymore
one option is to move it back after we are done.
|
|
! This isn’t usually what you want
for most cases you should use references and borrowing