7 min to read
Rust doc book note
- ownership
- Rust calls
drop
automatically at the closing curly bracket. - stack-only data
Copy
trait, older variable is still usable after assignment. - ownership and type systems
- Rust calls
- borrowing
&
is referencing,*
is dereferencing&str
ampersands are references, allow you to refer some value without taking ownership of it.&mut str
is mutable reference- slice
- at any given time, you can have either one mutable reference or any number of immutable references.
- references must always be valid.
- move
- 给变量换了个名字 原变量名失效
- stack-only data,
Copy
trait, still valid
- lifetime
- borrow checker借来的变量必须在变量的生命周期里
- input lifetimes: parameters; output lifetimes: return values;
- rule 1 each parameter that is a reference gets its own lifetime parameter.
fn foo<'a>(x: &'a i32)
;fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
; - rule 2 if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameter.
fn foo<'a>(x: &'a i32) -> &'a i32
; - rule 3 if there are multiple input lifetime parameters, but one of them is
&self
or&mut self
because this is a method, the lifetime ofself
is assigned to all output lifetime parameters. ' static
reference can live for the entire duration of the program.
- method
&self
immutable reference&mut self
mutable referenceself
consumer- associated functions
- closure
- anonymous functions that can capture their environment.
- lazy evaluation
- trait
- defining a Trait for common behavior
Copy
. 与Drop
互斥Clone
.clone
Deref
.deref
to behave like a reference. customize the behavior of the dereference operator,*
DerefMut
Drop
.drop
code that is run when a value goes out of scope. 需要做的额外的工作 释放堆上的数据. destructor methodIterator
.next
- trait object
- struct
- similar to tuples, the pieces of a struct can be different types. Unlike with tuples, you’ll name each piece of data
- unit-like struct
()
- tuple struct
struct MyBox<T>(T)
- zero-cost abstractions
- by which we mean using the abstraction imposes no additional runtime overhead
- In general, C++ implementations obey the zero-overhead principle: What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better. –defines zero-overhead in “Foundations of C++” (2012)
- pointer
- a variable that contains an address in memory. This address refers to, or “points at,” some other data.
- smart pointers
- data structures that not only act like a pointer but also have additional metadata and capabilities.
String
,Vec<T>
,Box<T>
,Rc<T>
,Ref<T>
,RefMut<T>
,RefCell<T>
- reference
- pointers that only borrow data. in contrast, in many cases, smart pointers own the data the point to.
- references must always be valid.
- regular reference or a type that implements
Deref
- associated types
- Deref coercion
- happens automatically when we pass a reference to a particular type’s value as an argument to a function or method
- reference
&
取地址 取引用 - dereference
*
取内容 解引用 - resolved at compile time, so there is no runtime penalty for taking advantage of deref coercion.
- From
&T
to&U
whenT: Deref<Target=U>
- From
&mut T
to&mut U
whenT: DerefMut<Target=U>
- From
&mut T
to&U
whenT: Deref<Target=U>
. - converting an immutable reference to a mutable reference would require that there is only one immutable reference to that data, and the borrowing rules don’t guarantee that. Rust can’t make the assumption that converting an immutable reference to a mutable reference is possible.
- reference counting.
Rc<T>
- 第一个人打开电视,最后一个人关闭电视
- only for use in single_threaded scenarios.
Rc::clone(&a)
doesn’t make a deep copy of all the data like most types’ implementations ofclone
do.- strong reference cycle can leak memory.
- interior mutating.
RefCell<T>
Weak<T>
- strong_count and weak_count; e.g. a parent node should own its children: if a parent node is dropped, its child nodes should be dropped as well. a child should not own its parent: if we drop a child node, the parent should still exist.
- concurrent and/or parallel
- thread
- race conditions,
- deadlocks,
- bugs that happen only in certain situations and are hard to reproduce and fix reliably
1:1
meaning one operating system thread per one language thread. Rust standard libraryM:N
model, the green-threaded model. there are crates that implementM:N
threading if you would rather trade overhead for aspects such as more control over which threads run when and lower costs of context switching,for example.
move
keyword- to force the closure to take ownership of the values it uses in the environment.
- message passing
- “Do not communicate by sharing memory; instead, share memory by communicating.” – Go LANG
- channel, has two halves: a transmitter and a receiver.
Mutex<T>
: mutual exclusion- you must attempt to acquire the lock before using the data.
- when you’re done with the data that the
mutex
guards, you must unlock the data so other threads can acquire the lock. - the call to
lock
returns a smart pointer calledMutexGuard
- implements
Deref
Drop
- provides interior mutability
- with risk of creating deadlocks (
Rc<T>
causing memory leak when reference cycle)
Arc<T>
atomically reference counted- thread safety comes with a performance penalty
Sync
andSend
Traits- allowing transference of ownership between threads with
Send
- allowing access from multiple threads with
Sync
- any type composed entirely of
Send
types is automatically marked asSend
as well - types composed entirely of types that are
Sync
are alsoSync
- allowing transference of ownership between threads with
- object-oriented, namely objects, encapsulation, inheritance,
- Object-oriented programs are made up of objects, An object packages data and the procedures that operate on that data. The procedures are typically called method or operations. – The Gang of Four book
- encapsulation: modules, types, functions, and methods are private default
- inheritance: 1. reuse of code 2. to enable a child type to be used in the same places as the parent type. this is also called polymorphism, which means that you can substitute multiple objects for each other at runtime if they share certain characteristics.
- bounded parametric polymorphism
- trait object
- a trait object points to both an instance of a type implementing out specified trait as well as a table used to look up trait methods on that type at runtime.
- trait objects are more like objects in other languages in the sense that they combine data and behavior.
- their specific purpose is to allow abstraction across common behavior.
- using generics and trait bounds will monomorphized at compile time to use the concrete types. static dispatch
- using trait objects, dynamic dispatch
- duck typing in dynamically typed languages: if it walks like a duck and quacks like a duck, then it must be a duck!
- a trait is object safe if all the methods defined in the trait have the following properties: 1. the return type isn’t
Self
. 2. there are no generic type parameters. the trait std::clone::Clone cannot be made into an object
break 1. the return type isn’tSelf
- pattern
- refutable and irrefutable
- macro
- metaprogramming
- in C++, macro 没有类型检查和函数调用开销(inline)
Comments