数组是相同类型对象的集合,并且在内存中是连续存放的.数组的创建用“[]”和数组的长度,长度是在编译时确定的, 定义数组用[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]);
}
本文介绍了数组和切片在编程中的概念和使用。数组是固定长度的相同类型元素集合,存储在栈上;切片则可以动态表示数组的一部分,其长度在运行时确定。切片通过数组指针和长度来定义,并且可以借用数组的一部分。示例代码展示了如何创建、初始化数组和切片,以及如何进行索引和长度查询。此外,还演示了数组切片的使用和越界访问的错误处理。
264

被折叠的 条评论
为什么被折叠?



