切片

切片能讓您查看更大的集合:

fn main() {
    let mut a: [i32; 6] = [10, 20, 30, 40, 50, 60];
    println!("a: {a:?}");

    let s: &[i32] = &a[2..4];

    println!("s: {s:?}");
}
  • 切片會從切片型別借用資料。
  • 問題:如果在輸出 s 前修改 a[3],會有什麼影響?
This slide should take about 10 minutes.
  • 我們會建立一個切片,方法是先借用 a,然後在括號中指定起始和結束索引。

  • 如果切片從索引 0 開始,Rust 的範圍語法可允許我們捨棄起始索引,也就是說,&a[0..a.len()]&a[..a.len()] 意思相同。

  • 同理,最後一個索引也是如此,因此 &a[2..a.len()]&a[2..] 意思相同。

  • 因此,為了輕鬆建立完整陣列的切片,我們可以使用 &a[..]

  • s 是對 i32s 切片的參照。請注意,s (&[i32]) 的型別不再提及陣列長度,這有利於我們對不同大小的切片執行運算。

  • Slices always borrow from another object. In this example, a has to remain 'alive' (in scope) for at least as long as our slice.

  • The question about modifying a[3] can spark an interesting discussion, but the answer is that for memory safety reasons you cannot do it through a at this point in the execution, but you can read the data from both a and s safely. It works before you created the slice, and again after the println, when the slice is no longer used.