Fundamentals Flashcards
Name the rules of ownership.
- Each value has a variable called its owner.
- There can only be one owner at a time.
- When an owner goes out of scope the value will be dropped
List all built-in copy types.
- booleans
- all integers
- all floats
- tuples of copy types
List the rules of references.
- At any given time, you can have either but not both of:
- One mutable reference
- Any number of immutable references
- References must always be valid
List all available enum variants.
- unit like (no arguments)
- tuple like (positional arguments)
- struct like (named arguments)
List the module rules.
- If module foo has no submodules put its definitions in a file named foo.rs
- If foo has submodules put its definitions in foo/mod.rs
List the privacy rules.
- pub items can be accessed by any parent module.
- everything else can only be accessed by their immediate parent module and all child modules.
Types allowing shared ownership.
- std::rc::RC / std::rc::Weak
- std::sync::Arc
How do Rc/Weak and Arc work?
- By implementing the Clone, Drop and Deref traits
- .clone() increments reference count
- .drop() decrements reference count
- other method calls are delegated to their contained value
- their own functionality is implemented as associated functions
Name two types that all enable interior mutability.
Cell & RefCell
How can you access a copy of the value contained in a Cell?
fn get(&self) -> T
with T: Copy
How can you change the value contained in a Cell?
fn set(&self, val: T)
with T: Copy
What is the difference between a Cell and a RefCell?
Cell does not let you call mut methods on it’s contained values and its values need to implement the Copy trait.
How can you get access to the value contained in a std::cell::RefCell?
- fn borrow(&self) -> Ref<t></t>
- fn try_borrow(&self) -> Result<ref>, BorrowError></ref>
- fn borrow_mut(&self) -> RefMut<t></t>
- fn try_borrow_mut(&self) -> Result<refmut>, BorrowMutError></refmut>
What happens when the rules of reference are violated with the help of a RefCell?
The borrow and borrow_mut methods panic.
How is the RefMut type used?
RefMut can be used as a mutable reference of the contained type.