Skip to content
🦀

Rust Cheat Sheet

Bảng Tóm Tắt Rust

A compact quick-reference for Rust syntax and common patterns. Bookmark this page for easy access while coding.

Variables & Types

Biến & Kiểu Dữ Liệu

let, mut, const, shadowing, primitives

let, mut, const, che khuất biến, kiểu nguyên thủy

rust
1let x = 5;          // immutable2let mut y = 10;      // mutable3const MAX: u32 = 100;4let x = x + 1;      // shadowing5// i32, f64, bool, char, &str, String

Functions

Hàm

fn, return types, closures

fn, kiểu trả về, hàm đóng

rust
1fn add(a: i32, b: i32) -> i32 {2    a + b // implicit return3}4let square = |x: i32| -> i32 { x * x };5let double = |x| x * 2; // type inferred

Control Flow

Luồng Điều Khiển

if/else, match, loop/while/for

if/else, match, vòng lặp

rust
1if x > 0 { "pos" } else { "neg" };2match value {3    1 => "one",4    2 | 3 => "few",5    _ => "other",6};7for item in &vec { /* ... */ }

Ownership & Borrowing

Quyền Sở Hữu & Mượn

move, clone, &ref, &mut ref, lifetimes

di chuyển, nhân bản, tham chiếu, tham chiếu mutable, vòng đời

rust
1let s1 = String::from("hi");2let s2 = s1;          // s1 moved3let s3 = s2.clone();  // deep copy4fn len(s: &str) -> usize { s.len() }5fn push(s: &mut String) { s.push('!'); }6fn first<'a>(s: &'a str) -> &'a str;

Structs & Enums

Struct & Enum

struct, impl, enum, Option, Result

cấu trúc, triển khai, liệt kê, Option, Result

rust
1struct Point { x: f64, y: f64 }2impl Point {3    fn new(x: f64, y: f64) -> Self {4        Self { x, y }5    }6}7enum Shape { Circle(f64), Rect(f64, f64) }

Error Handling

Xử Lý Lỗi

Result, ?, unwrap, expect, match

Result, ?, unwrap, expect, match

rust
1fn read() -> Result<String, io::Error> {2    let s = fs::read_to_string("f.txt")?;3    Ok(s)4}5let v = result.unwrap();    // panic if Err6let v = result.expect("msg");7let v = option.unwrap_or(0);

Collections

Bộ Sưu Tập

Vec, HashMap, String operations

Vec, HashMap, thao tác chuỗi

rust
1let mut v = vec![1, 2, 3];2v.push(4);3let mut map = HashMap::new();4map.insert("key", 42);5let s = String::from("hello");6let s2 = format!("{} {}", s, "world");

Traits & Generics

Trait & Generic

trait def, impl, where, dyn

định nghĩa trait, triển khai, ràng buộc, đa hình

rust
1trait Summary {2    fn summarize(&self) -> String;3}4impl Summary for Article { /* ... */ }5fn print<T: Summary>(item: &T) { /**/ }6fn render(item: &dyn Summary) { /**/ }

Common Macros

Macro Thông Dụng

println!, format!, vec!, assert!, dbg!

in ra, định dạng, tạo vector, kiểm tra, gỡ lỗi

rust
1println!("x = {x}, y = {}", y);2let s = format!("{:.2}", 3.14159);3let v = vec![1, 2, 3];4assert_eq!(2 + 2, 4);5dbg!(&my_struct);6todo!("implement later");

Cargo Commands

Lệnh Cargo

new, build, run, test, check, add, doc

tạo mới, build, chạy, kiểm thử, kiểm tra, thêm thư viện, tài liệu

rust
1cargo new my_project2cargo build --release3cargo run4cargo test5cargo check6cargo add serde --features derive7cargo doc --open
Built: 4/8/2026, 12:01:11 PM