Skip to content
เข้าสู่ระบบ

Unsafe Patterns

Patterns สำหรับ safe abstraction over unsafe code ใน Rust การใช้ unsafe ควรจำกัดให้น้อยที่สุดและ encapsulate ไว้หลัง safe APIs

unsafe keyword unlock 5 operations ที่ compiler ไม่สามารถ verify safety ได้

fn main() {
// Unsafe is needed for:
// 1. Dereference raw pointers
// 2. Call unsafe functions
// 3. Access mutable statics
// 4. Implement unsafe traits
// 5. Access union fields
// Example 1: Raw pointer dereference
let x = 42;
let ptr = &x as *const i32;
unsafe {
println!("Value via ptr: {}", *ptr);
}
// Example 2: Call unsafe function
unsafe fn dangerous() {
println!("Dangerous called!");
}
unsafe { dangerous(); }
// Example 3: Mutable static
static mut COUNTER: u32 = 0;
unsafe {
COUNTER += 1;
println!("Counter: {}", COUNTER);
}
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด