Rust Quick Reference
|
SharedRef |
MutableRef |
HeapOwned |
Sized |
Unsized |
Raw |
*const T |
*mut T |
Simple |
&T |
&mut T |
Box<T> |
T |
Trait* |
&Trait |
&mut Trait |
Box<Trait> |
|
Trait |
Array* |
&[T] |
&mut [T] |
Vec<T> |
[T; n] |
[T] |
String* |
&str |
&mut str |
String |
|
str |
Closure* |
Fn(T) -> U |
FnMut(T)->U |
FnOnce(T)->U |
fn(T)->U |
(*): fat pointers: contain (ptr, len) or (ptr, vtable) or environment.
TRAIT |
USAGE |
Value Semantics |
Clone |
.clone() makes a (usually deep) copy |
Copy |
Bitwise copy instead of moving. |
Drop |
Give specialized drop (i.e., destructor) behavior. |
Sized |
Size is statically known. (Automatically derived.) |
Misc |
IntoIterator |
Allows use in for loops. |
Error |
For errors. Has a description and a cause. |
Default |
fn default(&self) -> Self; |
Conversion |
Deref,DerefMut |
Overloads * and _._ and _._() . |
AsRef,AsMut |
Allows explicit conversion. Useful for flexible funcs. |
Borrow,BorrowMut |
Like AsRef and AsMut, but must have same hash! |
ToOwned |
Inverse of Borrow. |
From,Into |
Owned conversions. Implement From; Into is automatic. |
Closures |
Fn,FnMut,FnOnce |
Closure traits. Different than fn(T)->U func types. |
Concurrency |
Send |
Can be safely sent by value to another thread. |
Sync |
Can be safely sent by reference to another thread. |
TYPE |
USAGE |
Collections |
HashMap |
Map from keys to values. |
HashSet |
Set of values. |
BinaryHeap |
Priority queue. |
VecDequeue |
Double ended queue. |
Sharing |
Rc<T> |
Sharing when lifetime is statically unknown. Immutable. |
RefCell<T> |
Interior mutability via shared and mutable references. |
Cell<T> |
Owned interior mutability. fn update(&self, f: F)
where F: FnOnce(T)->T |
Concurrency |
Arc<T> |
Rc, but Send and Sync. Immutable. |
Mutex<T> |
Like RwLock, but deadlocks if there are ever two concurrent borrows. |
RwLock<T> |
RefCell, but Sync. Shared and mutable access. |
Sender,Receiver |
Channels. Multiple producer, single consumer. |
AtomicI32,etc. |
Atomic primitives. Concurrent mutable w/o data races. |
SYNTAX |
MEANING |
Comments |
/// TEXT |
#[doc = "TEXT"] |
//! TEXT |
#![doc = "TEXT"] |
Method Calls |
str::to_string("hello") |
"hello".to_string() , but qualified by type. |
ToString::to_string("hello") |
"hello".to_string() , but qualified by trait. |
Trait Bounds |
Trait1 + Trait2 |
Trait1 and Trait2 |
?Trait |
not necessarily Trait |
!Trait |
not Trait |
LIFETIME RULES
At all times, all values are in one of three states:
- Owned: The value is owned, and no one has a reference to it.
- Shared: There are one or more shared references to the value,
but no mutable references. No one can modify the value (or any value
reachable from it), not even its owner.
- Mutable: There is exactly one mutable reference to the value,
and no shared references. Its owner cannot read or write to the
value.
I constructed this quick reference using “Programming Rust”, by
Jim Blandy and Jason Orendorff.
January 25, 2020