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

Slice Primitives

Slice type [T] และ operations

fn main() {
// Slice from array
let arr = [1, 2, 3, 4, 5];
let slice: &[i32] = &arr[1..4];
println!("Slice [1..4]: {:?}", slice);
// Full slice
let full: &[i32] = &arr[..];
println!("Full slice: {:?}", 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);
// Slice from Vec
let vec = vec![10, 20, 30, 40, 50];
let slice: &[i32] = &vec[1..4];
println!("Vec slice: {:?}", slice);
// Mutable slice
let mut arr = [1, 2, 3, 4, 5];
let slice: &mut [i32] = &mut arr[1..4];
slice[0] = 20;
println!("Modified: {:?}", arr);
// Empty slice
let empty: &[i32] = &[];
println!("Empty: {:?}, len: {}", empty, empty.len());
// Slice is DST (Dynamically Sized Type)
println!("\nSize of &[i32]: {} bytes (fat pointer)",
std::mem::size_of::<&[i32]>());
}

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

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