ownership, references
This commit is contained in:
72
notes
72
notes
@ -138,3 +138,75 @@ syntax: for x in y {}
|
||||
|
||||
(start..end) is a Range
|
||||
(1..4).rev() is a thing
|
||||
|
||||
|
||||
https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html?search=
|
||||
ownership
|
||||
|
||||
stack - lifo in order memory storage, stack of PLATES
|
||||
pushing / popping
|
||||
all data stored here must have a FIXED size
|
||||
|
||||
heap - rando shit goes here
|
||||
allocating / deallocating
|
||||
pointer to data structure goes on the stack, the actual data goes on the heap
|
||||
|
||||
each value in Rust has an _owner_
|
||||
there can be only one owner at a time
|
||||
when the owner goes out of scope, the value goes out of scope
|
||||
|
||||
a string has 3 parts
|
||||
|
||||
name | val
|
||||
-----------
|
||||
ptr | ------> index | val
|
||||
len | 5 | -------------
|
||||
cap | 5 | | 0 | 'h' |
|
||||
----------- | 1 | 'e' |
|
||||
|
||||
|
||||
string2 = string1;
|
||||
create a new string data structure
|
||||
have the pointer point to the same data as string1
|
||||
|
||||
invalid:
|
||||
|
||||
s2 = s1;
|
||||
println!("{s1}");
|
||||
|
||||
there can't be two pointers to the same value!
|
||||
|
||||
shallow copy is a move because the first pointer is invalidated
|
||||
|
||||
clone is "deep copy"
|
||||
|
||||
s2 = s1.clone();
|
||||
|
||||
stack based vars don't need to clone, they `copy`, it's automatic
|
||||
|
||||
drop is called to return memory from the heap when it's owner goes out of scope
|
||||
|
||||
any type that implements the copy trait will auto copy.
|
||||
a type can not implement copy and drop...
|
||||
|
||||
tuples will copy if all of their types support it, it will not if any one of them does not
|
||||
|
||||
a function can take an immutable heap mounted variable and "recast" it is mutable
|
||||
|
||||
https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html
|
||||
references
|
||||
|
||||
rust has a method to let a function use a variable without moving / reassigning
|
||||
ownership: references
|
||||
|
||||
& is a reference
|
||||
* is a dereference
|
||||
|
||||
pass a reference to avoid _moving_ the value
|
||||
references are immutable by default
|
||||
|
||||
&mut var // makes a mutable reference
|
||||
|
||||
there can be one or multiple r/o references or only one mutable reference at a time
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user