Rust數組和切片

Rust數組和切片

數組是同一類型的對象的集合 T, 存儲在連續內存中。 用方括號 [] 創建數組, 以及它們的大小在編譯的時候判定,是它們的類型簽名的一部分 [T; size].

切片和數組相似,但它們的大小在編譯時是不知道的. 相反,切片是一個雙字對象,第一個字是一個指針中的數據,第二個字是切片的長度。切片可借用數組的截面,並具有式簽名 &[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\]);

}

0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder