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 printings
?
-
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 voni32
. Beachte, dass der Typs
(&[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 througha
at this point in the execution, but you can read the data from botha
ands
safely. It works before you created the slice, and again after theprintln
, when the slice is no longer used.