Slice Structs
Slice types และ related structs ใน Rust ให้วิธีทำงานกับ contiguous sequences ของ elements โดยไม่ต้อง own data ทั้ง &[T] (immutable slice) และ &mut [T] (mutable slice) เป็น fundamental types ที่ใช้กันทั่วไป
1. Slice Basics
Section titled “1. Slice Basics”Slices เป็น Dynamically Sized Types (DST) ที่ต้องใช้ผ่าน references เสมอ ประกอบด้วย pointer และ length (fat pointer)
การสร้าง Slices
Section titled “การสร้าง Slices”fn main() { let arr = [1, 2, 3, 4, 5];
// Slice from array with range let slice: &[i32] = &arr[1..4]; println!("Slice: {:?}", slice); // [2, 3, 4]
// Full slice (all elements) let full: &[i32] = &arr[..]; println!("Full: {:?}", full);
// From start let from_start: &[i32] = &arr[..3]; println!("From start: {:?}", from_start);
// To end let to_end: &[i32] = &arr[2..]; println!("To end: {:?}", to_end);
// Empty slice let empty: &[i32] = &[]; println!("Empty: {:?}, len: {}", empty, empty.len());}เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google