Pointers - พอยน์เตอร์
std::ptr module สำหรับจัดการ raw pointers ใน Rust ใช้สำหรับ low-level memory operations, FFI, และการสร้าง custom data structures
ptr คืออะไร?
Section titled “ptr คืออะไร?”Raw pointers ใน Rust มี 2 ชนิด:
*const T- pointer อ่านอย่างเดียว (immutable raw pointer)*mut T- pointer แก้ไขได้ (mutable raw pointer)
ความแตกต่างจาก References
Section titled “ความแตกต่างจาก References”fn main() { // ============================================ // References (&T, &mut T) มีการ์ดจาก compiler // ============================================
// - ต้อง valid (point to allocated memory) // - ต้อง aligned // - lifetime ถูกตรวจสอบ // - borrowing rules ถูก enforce
// ============================================ // Raw Pointers (*const T, *mut T) ไม่มีการ์ด // ============================================
// - อาจ null // - อาจ dangling (point to freed memory) // - อาจ unaligned // - ไม่มี lifetime tracking // - หลาย *mut T ไปที่เดียวกันได้
let x = 42; let ref_x: &i32 = &x; // Safe reference let ptr_x: *const i32 = &x; // Raw pointer
println!("ref_x: {}", ref_x); println!("ptr_x: {:p}", ptr_x);
// Dereference pointer ต้องใช้ unsafe! unsafe { println!("*ptr_x: {}", *ptr_x); }}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google