Chuyển tới nội dung chính

Rust Cheatsheet

Tra cứu nhanh các lệnh Cargo, cú pháp xử lý lỗi, serde, và quy trình kiểm tra code Rust hằng ngày.

Lệnh Cargo & Kiểm tra chất lượng​

cargo new my-app # Tạo binary crate mới
cargo build --release # Biên dịch bản tối ưu
cargo run # Biên dịch và chạy
cargo check # Kiểm tra compile nhanh (không sinh binary)
cargo test --workspace # Chạy toàn bộ test trong workspace
cargo fmt --all --check # Kiểm tra format code
cargo clippy --workspace --all-targets -- -D warnings # Lint chặt như CI

Xử lý Option & Result​

use std::fs;
use std::io;

fn read_config(path: &str) -> Result<String, io::Error> {
let content = fs::read_to_string(path)?; // Tự trả Err nếu thất bại
Ok(content)
}

let port = std::env::var("APP_PORT").unwrap_or_else(|_| "8080".to_string());

Ownership & Borrowing tóm tắt​

Cú phápÝ nghĩa
TChuyển quyền sở hữu (move)
&TMượn bất biến (có thể nhiều &T cùng lúc)
&mut TMượn khả biến (chỉ duy nhất 1 &mut T tại một thời điểm)
String vs &strChuỗi sở hữu trên heap vs slice tham chiếu chuỗi
Vec<T> vs &[T]Mảng động sở hữu vs slice tham chiếu mảng

Serialize / Deserialize với serde​

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct DeviceConfig {
name: String,
baud: u32,
}

Kiểm tra Dependency & Security​

cargo deny --workspace check # Kiểm tra license, advisory và nguồn crate
cargo audit # Quét lỗ hổng bảo mật (RustSec)

Tham khảo​