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

切片类型

Syntax
SliceType[ Type ]

切片是动态大小类型,表示类型为 T 的元素序列的“视图“。切片类型写为 [T]

切片类型通常通过指针类型使用。例如:

  • &[T]:“共享切片”,通常简称为“切片“。它不拥有它指向的数据;它借用它。
  • &mut [T]:“可变切片”。它可变地借用它指向的数据。
  • Box<[T]>:“装箱切片”

示例:

#![allow(unused)]
fn main() {
// A heap-allocated array, coerced to a slice
let boxed_array: Box<[i32]> = Box::new([1, 2, 3]);

// A (shared) slice into an array
let slice: &[i32] = &boxed_array[..];
}

切片的所有元素始终是已初始化的,并且在安全方法和运算符中对切片的访问始终进行边界检查。