This table of contents serves mostly to write down how we want to structure the document.
- Simple example
- What is a resource?
- Memory as a resource
- Example
- Garbage collectors
- Static memory, stack, heap
- Recap (TODO)
- Simple example
- Ownership: responsibility for closing a resource
- Borrowing: using a resource (TODO)
- Borrowing as immutable: non-exclusive usage, read-only
- Borrowing as mutable: exclusive usage, allowing writes
- Moving: transfer of ownership (TODO)
- Move semantics: only one owner may be responsible
- Copy semantics: not all data types correspond to owners of a resource
- Encapsulation prevents fiddling with the resource from outside (is now DRAFT)
- Example
- Handles are stored in private fields to prevents fiddling from outside
- Asking for an
&mut
parameters when you offer something exclusive
- Recap
- Examples of owners
String
Box<T>
Vec<T>
- ...
- Initialising a value is opening a resource
- Resources are released when the owner goes out of scope
- When a value that is no owner anymore goes out of scope, no resource is released (that is the responsibility of the new owner now)
- Named variables: at the end of lexical scope, in reversed order
- Anonymous variables (temporaries): at the end of the statement
- Temporaries in the condition of an
if
or awhile
- Exception
- Temporaries in the condition of an
- Resources in fields are released after the containing struct is released
- Drop order of fields
mem::drop()
Rc<T>
andArc<T>
allow to decide at run-time when a resource must be released- Resources leak when they are not released
mem::forget
- cyclic references with
Rc<T>
andArc<T>
cause leaks
- Recap
- Examples of borrowing
- functions with an
&
or an&mut
parameter - references
- structs and enums etc. may borrow when they contain a reference
- closures may borrow
- functions with an
- Slices
Box<T>
is an owner ofT
and&T
and&mut T
are borrowersString
is an owner and&str
is a borrower- Interaction with ownership
- you may only use a resource that has been opened
- you must finish using a resource before it is released
- Returning a
Box<T>
instead of an&T
- Returning a
- Partially borrowing
- of a struct
- of a slice:
split_at()
andsplit_at_mut()
- compound data-types make partially borrowing easier
- Interior mutability: checking access at run time instead of compile-time
Cell
Refcell
Mutex
RwLock
- Recap
- Examples of moving
- returning from a function
- result of an expression
- passing a parameter to a function
- moving closure
- Copy semantics: not all data types correspond to owners of a resource
- Interaction with ownership: the old owner does not need to release the resource anymore
- Interaction with borrowing: cannot move out of borrowed content
mem::swap()
andOption::take()
- Recap
TODO