Rust - 切片 (Slices)



切片是指向一塊記憶體區域的指標。切片可以用來訪問儲存在連續記憶體塊中的部分資料。它可以與陣列、向量和字串等資料結構一起使用。切片使用索引號來訪問部分資料。切片的大小在執行時確定。

切片是指向實際資料的指標。它們透過引用傳遞給函式,這也稱為借用。

例如,切片可以用來獲取字串值的一部分。切片字串是指向實際字串物件的指標。因此,我們需要指定字串的起始和結束索引。索引從 0 開始,就像陣列一樣。

語法

let sliced_value = &data_structure[start_index..end_index]

最小索引值為 0,最大索引值為資料結構的大小。注意,`end_index` 將不會包含在最終字串中。

下圖顯示了一個示例字串 Tutorials,它有 9 個字元。第一個字元的索引為 0,最後一個字元的索引為 8。

String Tutorials

以下程式碼從字串中獲取 5 個字元(從索引 4 開始)。

fn main() {
   let n1 = "Tutorials".to_string();
   println!("length of string is {}",n1.len());
   let c1 = &n1[4..9]; 
   
   // fetches characters at 4,5,6,7, and 8 indexes
   println!("{}",c1);
}

輸出

length of string is 9
rials

圖示 - 切片整數陣列

main() 函式聲明瞭一個包含 5 個元素的陣列。它呼叫 use_slice() 函式,並向其傳遞三個元素的切片(指向資料陣列)。切片透過引用傳遞。use_slice() 函式列印切片的值及其長度。

fn main(){
   let data = [10,20,30,40,50];
   use_slice(&data[1..4]);
   //this is effectively borrowing elements for a while
}
fn use_slice(slice:&[i32]) { 
   // is taking a slice or borrowing a part of an array of i32s
   println!("length of slice is {:?}",slice.len());
   println!("{:?}",slice);
}

輸出

length of slice is 3
[20, 30, 40]

可變切片

可以使用 &mut 關鍵字將切片標記為可變的。

fn main(){
   let mut data = [10,20,30,40,50];
   use_slice(&mut data[1..4]);
   // passes references of 
   20, 30 and 40
   println!("{:?}",data);
}
fn use_slice(slice:&mut [i32]) {
   println!("length of slice is {:?}",slice.len());
   println!("{:?}",slice);
   slice[0] = 1010; // replaces 20 with 1010
}

輸出

length of slice is 3
[20, 30, 40]
[10, 1010, 30, 40, 50]

上面的程式碼將可變切片傳遞給 use_slice() 函式。該函式修改了原始陣列的第二個元素。

廣告
© . All rights reserved.