Rust数组和切片
数组是同一类型的对象的集合%uA0T
, 存储在连续内存中。 用方括号%uA0[]
创建数组, 以及它们的大小在编译的时候判定,是它们的类型签名的一部分%uA0[T size]
.
切片和数组相似,但它们的大小在编译时是不知道的. 相反,切片是一个双字对象,第一个字是一个指针中的数据,第二个字是切片的长度。切片可借用数组的截面,并具有式签名%uA0&[T]
.
use std::mem // This function borrows a slice fn analyze_slice(slice: &[i32]) { println!("first element of the slice: {}", slice[0]) println!("the slice has {} elements", slice.len()) } fn main() { // Fixed-size array (type signature is superfluous) let xs: [i32 5] = [1, 2, 3, 4, 5] // All elements can be initialized to the same value let ys: [i32 500] = [0 500] // Indexing starts at 0 println!("first element of the array: {}", xs[0]) println!("second element of the array: {}", xs[1]) // `len` returns the size of the array println!("array size: {}", xs.len()) // Arrays are stack allocated println!("array occupies {} bytes", mem::size_of_val(&xs)) // Arrays can be automatically borrowed as slices println!("borrow the whole array as a slice") analyze_slice(&xs) // Slices can point to a section of an array println!("borrow a section of the array as a slice") analyze_slice(&ys[1 .. 4]) // Out of bound indexing yields a panic println!("{}", xs[5]) }