# Rust Std Docs
# Cell
# String
# &str
// string literal
let s2: &str = "Hello, world!";
1
2
2
- &str is stored directly in the compiled binary.
- Stored in Text/Code segment.
- &str has a static lifetime. They are never deallocated.
# Misconceptions
Phrase | Shorthand for |
---|---|
T | 1) a set containing all possible types or 2) some type within that set |
owned type | some non-reference type, e.g. i32 , String , Vec , etc |
1) borrowed type or 2) ref type | some reference type regardless of mutability, e.g. &i32 , &mut i32 , etc |
1) mut ref or 2) exclusive ref | exclusive mutable reference, i.e. &mut T |
1) immut ref or 2) shared ref | shared immutable reference, i.e. &T |
# T, &T, &mut T
- T is a superset of both &T and &mut T
- &T and &mut T are disjoint sets
# T: 'static
- T: 'static should be read as "T is bounded by a 'static lifetime"
- if T: 'static then T can be a borrowed type with a 'static lifetime or an owned type
- since T: 'static includes owned types that means T
- can be dynamically allocated at run-time
- does not have to be valid for the entire program
- can be safely and freely mutated
- can be dynamically dropped at run-time
- can have lifetimes of different durations
# &‘a T and T: 'a
- T: 'a is more general and more flexible than &'a T
- T: 'a accepts owned types, owned types which contain references, and references
- &'a T only accepts references
- if T: 'static then T: 'a since 'static >= 'a for all 'a
# lifetime
- almost all Rust code is generic code and there's elided lifetime annotations everywhere
- Rust's lifetime elision rules for functions are not always right for every situation
- Rust does not know more about the semantics of your program than you do
- give your lifetime annotations descriptive names
- try to be mindful of where you place explicit lifetime annotations and why
- all trait objects have some inferred default lifetime bounds
- Rust's lifetime elision rules for trait objects are not always right for every situation
- Rust does not know more about the semantics of your program than you do
- Rust compiler error messages suggest fixes which will make your program compile which is not that same as fixes which will 1. make you program compile and best suit the requirements of your program
- lifetimes are statically verified at compile-time
- lifetimes cannot grow or shrink or change in any way at run-time
- Rust borrow checker will always choose the shortest possible lifetime for a variable assuming all code paths can be taken
- try not to re-borrow mut refs as shared refs, or you're gonna have a bad time
- re-borrowing a mut ref doesn't end its lifetime, even if the ref is dropped
# lifetime: outlives
'long: 'short
is read "'long outlives 'short".
'a:'b
means that the lifetime 'a outlives the lifetime 'b
# Closure
一个闭包实现了哪种 Fn 特征取决于该闭包如何使用被捕获的变量,而不是取决于闭包如何捕获它们。move
本身强调的就是后者,闭包如何捕获变量