切片
切片 (slice) 的作用是提供对集合 (collection) 的视图 (view):
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:?}"); }
- 切片从被切片的类型中借用 (borrow) 数据。
- Question: What happens if you modify
a[3]
right before printings
?
-
We create a slice by borrowing
a
and specifying the starting and ending indexes in brackets. -
If the slice starts at index 0, Rust’s range syntax allows us to drop the starting index, meaning that
&a[0..a.len()]
and&a[..a.len()]
are identical. -
The same is true for the last index, so
&a[2..a.len()]
and&a[2..]
are identical. -
To easily create a slice of the full array, we can therefore use
&a[..]
. -
s
is a reference to a slice ofi32
s. Notice that the type ofs
(&[i32]
) no longer mentions the array length. This allows us to perform computation on slices of different sizes. -
Slices always borrow from another object. In this example,
a
has to remain ‘alive’ (in scope) for at least as long as our slice. -
关于修改“a[3]”的问题可能会引发一些有趣的讨论,但正解是,出于内存安全方面的原因,您无法在执行作业的这个时间点通过“a”来进行此修改,但可以从“a”和“s”安全地读取数据。它会在您创建 Slice 之前运作,在“println”之后(不再使用 Slice 时)再次运作。更多详情会在“借用检查器”部分中加以说明。