Rust CheatSheet 是对于 Rust 学习/实践过程中的语法与技巧进行盘点,其属于 Awesome CheatSheet 系列,致力于提升学习速度与研发效能,即可以将其当做速查手册,也可以作为轻量级的入门学习资料。本文参考了许多优秀的文章与代码示范,统一声明在了 Awesome Rust List;如果希望深入了解某方面的内容,可以继续阅读Rust-Series,或者前往 rust-examples 查看使用 Rust 解决常见的数据结构与算法、设计模式、业务功能方面的代码实现。
Rust 是为工业应用而生,并不拘泥于遵循某个范式(Paradigm),笔者认为其最核心的特性为 Ownership 与 Lifetime;能够在没有 GC 与 Runtime 的情况下,防止近乎所有的段错误,并且保证线程安全(prevents nearly all segfaults, and guarantees thread safety)。Rust 为每个引用与指针设置了 Lifetime,对象则不允许在同一时间有两个和两个以上的可变引用,并且在编译阶段即进行了内存分配(栈或者堆);Rust 还提供了 Closure 等函数式编程语言的特性、编译时多态(Compile-time Polymorphism)、衍生的错误处理机制、灵活的模块系统等。
对于 Rust 的语法速览可以参考本目录下的 rust-snippets。
fn main() {println!("Hello, world!");}
Example | Explanation |
| Line comment, use these to document code flow or internals. |
| Outer line doc comment, use these on types. |
| Inner line doc comment, mostly used at start of file to document module. |
| Block comment. |
| Outer block doc comment. |
| Inner block doc comment. |
| In doc comments, include a doc test (doc code running on |
| In doc tests, hide line from documentation ( |
通过关键字定义的数据类型和存储位置。
Example | Explanation |
| Define a struct with named fields. |
| Define struct with named field |
| Define "tupled" struct with numbered field |
| Define zero sized unit struct. Occupies no space, optimized away. |
| Define an enum, c. algebraic data types, tagged unions. |
| Define variants of enum; can be unit- |
| If variants are only unit-like, allow discriminant values, e.g., for FFI. |
| Unsafe C-like union for FFI compatibility. |
| Global variable with |
| Defines constant . Copied into a temporary when used. |
| Allocate |
| Like |
| Moves |
绑定变量(Bound Variables)存在于堆栈中,用于同步代码。在 async {}
代码中,它们成为异步状态机的一部分,可能驻留在堆上。从技术上讲,可变性和不变性是误称。不可变的绑定或共享引用可能仍包含 Cell,从而提供内部可变性。创建和访问数据结构;以及其他一些西语类型。
Example | Explanation |
| Create |
| Same, but use local variable |
| Fill remaining fields from |
| Like |
| Create |
| If |
| Create enum variant |
| Empty tuple, both literal and type, aka unit. |
| Parenthesized expression. |
| Single-element tuple expression. |
| Single-element tuple type. |
| Array type of unspecified length, i.e., slice. Can't live on stack. |
| Array type of fixed length |
| Array instance with |
| Array instance with given elements |
| |
| Collection slice-like indexing via RangeFull, c. slices. |
| Collection slice-like indexing via RangeFrom. |
| Collection slice-like indexing RangeTo. |
| Collection slice-like indexing via Range. |
| Right-exclusive range creation, also seen as |
| Inclusive range creation, also seen as |
| Named field access, might try to Deref if |
| Numbered field access, used for tuple types |
这些签名不适合任何其他类别,但是很高兴知道。
Example | Explanation | | |
| Always empty never type. | | |
| Unnamed variable binding, e.g., ` | x, _ | {}`. |
| Unnamed assignment is no-op, does not move out | | |
| Variable binding explicitly marked as unused. | | |
| Numeric separator for visual clarity. | | |
| Type specifier for numeric literals (also | | |
| Hexadecimal ( | | |
| A raw identifier for edition compatibility. | | |
| Statement terminator, c. expressions | | |
授予对未拥有的内存的访问权限。另请参见“泛型和约束”部分。
Example | Explanation |
| Shared reference (space for holding any |
| Special slice reference that contains ( |
| Special string reference that contains ( |
| Exclusive reference to allow mutability (also |
| Special trait object reference that contains ( |
| Immutable raw pointer type w/o memory safety. |
| Mutable raw pointer type w/o memory safety. |
| Shared borrow (e.g., address, len, vtable, ... of this |
| Exclusive borrow that allows mutability. |
| Bind by reference. |
| Equivalent to |
| Mutable ref binding ( |
| Dereference a reference |
| If |
| Make |
| Special case for |
| A lifetime parameter,, duration of a flow in static analysis. |
| Only accepts a |
| Same, but allow content of address to be changed. |
| Signals |
| Signals a |
| Same, for function. Caller decides |
| Special lifetime lasting the entire program execution. |
类型的简写名称,以及将一种类型转换为另一种类型的方法。
Example | Explanation |
| Create a type alias, i.e., another name for |
| Type alias for implementing type, e.g. |
| Method subject in |
| Same, but refers to self as borrowed, same as |
| Same, but mutably borrowed, same as |
| Arbitrary self type, add methods to smart pointers ( |
| Disambiguate type |
| In |
| Primitive cast, may truncate and be a bit surprising. |
定义代码单元及其抽象。
Example | Explanation | | |
| Define a trait; common behavior others can implement. | | |
|
| | |
| Implementation of functionality for a type | | |
| Implement trait | | |
| Disable an automatically derived auto trait . | | |
| Definition of a function; or associated function if inside | | |
| Same, returning a value of type S. | | |
| Define a method, e.g., within an | | |
| Constant | | |
| Async function transformation, makes | | |
| Same, but make | | |
| Used within a function, make | | |
| Function pointers,, memory holding address of a callable. | | |
| Callable Trait, (also | | |
` | | {}` | A closure that borrows its captures. |
` | x | {}` | Closure with a bound parameter |
` | x | x + x` | Closure without block expression; may only consist of single expression. |
`move | x | x + y` | Closure taking ownership of its captures. |
`return | | true` | Closures sometimes look like logical ORs (here: return a closure). |
| If you enjoy debugging segfaults Friday night; unsafe code. | | |
| Sort-of means "can cause UB, YOU must check requirements". | | |
| Guarantees to compiler "*I have checked requirements, trust me*". | | |
Example | Explanation |
| Loop, run while expression |
| Loop infinitely until |
| Syntactic sugar to loop over iterators. |
| Conditional branch if expression is true. |
| Loop label, useful for flow control in nested loops. |
| Break expression to exit a loop. |
| Same, but make |
| Exit not only this loop, but the enclosing one marked with |
| Continue expression to the next loop iteration of this loop. |
| Same, but instead of enclosing loop marked with |
| |
| Only works inside |
| Early return from function. More idiomatic way is to end with expression. |
| Invoke callable |
| Call member function, requires |
| Same as |
| Same as |
| Same as |
| Same as |
| Same as |
| Call associated function, e.g., |
| Call trait method |
在 match 或 let 表达式或函数参数中找到的构造。
Example | Explanation |
| Initiate pattern matching, then use match arms, c. next table. |
| Notably, |
| Only |
| Only |
| Ignoring 'the rest' also works. |
| Specific bindings take precedence over 'the rest', here |
| Won't work if pattern can be refuted, use |
| Branch if pattern can be assigned (e.g., |
| Function parameters also work like |
匹配表达式中的模式匹配臂。这些臂的左侧也可以在 let 表达式中找到。
Match Arm | Explanation | |
| Match enum variant | |
| Match enum tuple variant | |
| Match enum struct variant | |
| Match struct with specific values (only accepts | |
| Match struct with any(!) values and bind | |
| Same, but shorthand with | |
| Match struct with any values. | |
| Match enum variant | |
| Match anything, bind | |
| Proper wildcard that matches anything / "all the rest". | |
| Match tuple with any value for | |
| Slice pattern, match array with any value for | |
| Match array starting with | |
| Match array starting with | |
| Same, but also bind | |
| Bind matched to | |
`0 | 1 => {}` | Pattern alternatives (or-patterns). |
`E::A | E::Z` | Same, but on enum variants. |
`E::C {x} | E::D {x}` | Same, but bind |
| Pattern match guards, condition must be true as well to match. | |
代码生成结构在实际编译发生之前就已扩展。
Example | Explanation |
| Macro invocation, also |
| Outer attribute., annotating the following item. |
| Inner attribute, annotating the surrounding item. |
在声明性宏中的示例 macro_rules!实现这些工作:
Within Macros | Explanation |
| Macro capture, with the |
| An item, like a function, struct, module, etc. |
| A block |
| A statement, e.g., |
| An expression, e.g., |
| A pattern, e.g., |
| A type, e.g., |
| An identifier, for example in |
| A path (e.g. |
| A literal (e.g. |
| A lifetime (e.g. |
| A meta item; the things that go inside |
| A visibility modifier; |
| A single token tree, see here for more details. |
| Macro substitution, e.g., use the captured |
| Macro repetition "zero or more times" in macros by example. |
| Same, but "zero or one time". |
| Same, but "one or more times". |
| In fact separators other than |
| Special hygiene variable, crate where macros is defined. |
Generics combine with many other constructs such as struct S, fn f(), ...
Example | Explanation |
| A generic type with a type parameter ( |
| Type short hand trait bound specification ( |
| Independent trait bounds (here one for |
| Compile error, you probably want compound bound |
| Compound trait bound, |
| Same, but w. lifetime. |
| Opt out of a pre-defined trait bound, here |
| Type lifetime bound ; if T has references, they must outlive |
| Same; does esp. not mean value |
| Lifetime |
| Same as |
| Default type parameter for associated type. |
| Inferred anonymous lifetime; asks compiler to 'figure it out' if obvious. |
| Inferred anonymous type, e.g., as |
| Turbofish call site type disambiguation, e.g. |
| A trait generic over |
| Defines associated type |
| Set associated type within |
| Implement functionality for any |
| Implement functionality for exactly |
| Existential types, returns an unknown-to-caller |
| Trait bound,"impl traits", somewhat similar to |
| Marker for dynamic dispatch, |
| In |
| Esp. useful w. default methods (non dflt. would need be impl'ed anyway). |
| Higher-ranked trait bounds. |
| Any |
将项目分割成较小的单元,并最大程度地减少依赖性。
Example | Explanation |
| Define a module, get definition from inside |
| Define a module, get definition from |
| Namespace path to element |
| Search |
| Search |
| Search |
| Search |
| Use |
| Same, but bring |
| Bring |
| Bring |
| Bring everything from |
| Bring |
| "Public if parent path is public" visibility for |
| Visible at most in current crate. |
| Visible at most in current module. |
| Visible at most in parent. |
| Visible at most in |
| Declare dependency on external crate ; just |
| Declare external dependencies and ABI (e.g., |
| Define function to be exported with ABI (e.g., |
Example | Explanation |
| String literal, UTF-8, will interpret |
| Raw string literal. UTF-8, won't interpret |
| Raw string literal, UTF-8, but can also contain |
| Byte string literal; constructs ASCII |
| Raw byte string literal, ASCII |
| Character literal, fixed 4 byte unicode 'char'. |
| ASCII byte literal. |