Anteilstypen

Ein Anteilstyp (slice) gibt Ihnen einen Einblick in eine grĂ¶ĂŸere Sammlung (collection):

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:?}");
}
  • Anteilstypen (slices) borgen (borrow) Daten vom Sliced-Typ.
  • Question: What happens if you modify a[3] right before printing s?
This slide should take about 10 minutes.
  • Wir erstellen ein Anteilstyp, indem wir a ausleihen (borrow) und den Start- und Endindex in Klammern angeben.

  • Wenn der Anteilstyp bei Index 0 beginnt, erlaubt uns die Range-Syntax von Rust, den Startindex wegzulassen, was bedeutet, dass &a[0..a.len()] und &a[..a.len()] identisch sind.

  • Das Gleiche gilt fĂŒr den letzten Index, daher sind &a[2..a.len()] und &a[2..] identisch.

  • Um einfach einen Anteilstyp des gesamten Arrays zu erstellen, können wir daher „&a[..]“ verwenden.

  • s ist ein Verweis (reference) auf einen Teil von i32. Beachte, dass der Typ s (&[i32]) die Array-LĂ€nge nicht mehr erwĂ€hnt. Dadurch können wir Berechnungen fĂŒr Anteilstypen unterschiedlicher GrĂ¶ĂŸe durchfĂŒhren.

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