数组是相同类型对象的集合,并且在内存中是连续存放的.数组的创建用“[]”和数组的长度,长度是在编译时确定的, 定义数组用[T, length]
切片和数组相似,但是他们的长度在编译时是不能确定的.切换是两个对象组成的,第一个对象是数组指针,第二个是切片的长度. 长度用是usize,具体长度由处理器架构确定,例如在x86-64 用64bit.切片可以借用数组的一部分,并且数据类型为&[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 count of elements in the array
println!("number of elements in array: {}", 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
// They are of the form [starting_index..ending_index]
// starting_index is the first position in the slice
// ending_index is one more than the last position in the slice
println!("borrow a section of the array as a slice");
analyze_slice(&ys[1 .. 4]);
// Out of bound indexing causes compile error
println!("{}", xs[5]);
}