Skip to content

🌑 The Dark Arts

"Sức mạnh lớn đi kèm trách nhiệm lớn." - Unsafe Rust manual

Tổng quan Module


📚 Nội dung Module

1. Metaprogramming

  • Declarative Macros (macro_rules!)
  • Procedural Macros
  • Thao tác AST (Derive, Attribute)

2. Unsafe Rust

  • Raw Pointers (*const T, *mut T)
  • FFI (Foreign Function Interface)
  • std::mem::transmute

⚠️ Khi nào cần Unsafe?

Tình huốngCần Unsafe?Giải thích
FFI / Gọi C✅ CóCompiler không verify C code
Custom allocator✅ CóThao tác memory cấp thấp
Lock-free data structures✅ CóAtomic operations + raw pointers
Tối ưu hiệu năng⚠️ Có thểProfile trước, unsafe sau cùng
"Tôi biết hơn compiler"❌ Hiếm khiThường là giả định sai

🛡️ Safety Contract

rust
// Unsafe chỉ là "tin tôi đi" cho compiler
// BẠN chịu trách nhiệm đảm bảo safety invariants

unsafe {
    // Bạn đang nói: "Tôi đã verify rằng code này an toàn"
    // Compiler sẽ không kiểm tra cho bạn
    // Nếu sai → Undefined Behavior
}