learning rust
cheat sheet
question
- rust questions and syntax questions
- repasar error handling
- lifetimes
- closures
error handling
Rust has 2 types that allow or represent two things that could occurr
Option<T,None>
operations that can do nothing, like a function that returns a value through parsing and nothing is there
and Result<V,E>
operations that can pass or fail
// Option<T> -> Some (T), None
fn can_do_nothing() -> Option<i32> {
None
}
// Result<v, E>
fn can_fail() -> Result<132, &'static str> {
Err ("oops")
}
unwrap()
unwraps values inside Some() or Okay()
unwrap caused a big cloudflare outage and people suggested renaming
unwrap to .or_panic()
and .expect() to .or_panic_with()
rename unwrap() to or_panic().
And .expect) to .or_panic_with().
"Unwrap" is a terrible name for the panicking function, especially since we also have things like unwrap_or() and unwrap_or_default() which never panic.
smart pointers
Box allocates memory to the heap instead of the stack. Allocating mem to the stack is much faster but in some cases it can't be possible.
Box is a single ownership pointer.
2 cases to use box:
implementing a trait of a struct that the compiler can't guess the size of at compile time. ex: I have struct Vehicle and traits Car and Truck. if I make a let my_vehicle: Vehicle. and in the next line my_v = new (Truck). thows error. need to use Box
recursive data types: when I have a daty type that has a parameter of the same type. ex: Truck that has a param next_truck_in_line:Truck
Rc reference counter.
is a smart pointer that allows multiple owners of the same value. When all the owners/copies die, the Rc is dropped.
Arc is an rc that is thread safe. allows being sent and received to/from other threads
RefCell functions like Box but borrowing rules are enforced at runtime instead of compile time.
single ownership
This is useful when:
I'm sure my program is mem safe and the compiler can't understand that. Can only use this pointer in single threaded programs.
borrow() method to get an inmutable reference and borrow_mut() to get a mutable reference.
There are two ways to calls smart pointers functions: value.clone() or Rc::clone(value). Using the second one is convention to not confuse possible methods contained in value named the same