Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Wycinki

Wycinek daje wgląd w większą kolekcję:

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:?}");
}
  • Wycinki pożyczają dane od ciętego typu.
  • Question: What happens if you modify a[3] right before printing s?
This slide should take about 10 minutes.
  • Tworzymy wycinek, pożyczając a i określając indeksy początkowe i końcowe w nawiasach.

  • Jeśli wycinek zaczyna się od indeksu 0, składnia zakresu Rusta pozwala nam pominąć indeks początkowy, co oznacza, że &a[0..a.len()] i &a[..a.len()] są identyczne .

  • To samo dotyczy ostatniego indeksu, więc &a[2..a.len()] i &a[2..] są identyczne.

  • Aby łatwo utworzyć wycinek pełnej tablicy, możemy zatem użyć &a[..].

  • s jest referencją do wycinka elementów i32. Zauważ, że typ s (&[i32]) nie wspomina już o długości tablicy. To pozwala nam wykonywać obliczenia na wycinkach o różnych rozmiarach.

  • 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.