Rust 程式設計中的切片
Rust 中的切片是相同資料型別 T 的元素集合,但與陣列不同,不必在編譯時就知道它們的長度。
在 Rust 中,切片是一個由兩個單詞構成物件,其中第一個單詞實際上指向資料,第二個單詞只是切片長度。
切片比陣列安全得多,並且可以在不進行復制的情況下高效地訪問陣列。切片由陣列、字串建立。它們既可以是可變的,也可以是不可變的。切片通常是指陣列或字串的切片。
範例
fn main() { let xs: [i32; 5] = [1, 2, 3, 4, 5]; let slice = &xs[1..5]; println!("first element of the slice: {}", slice[0]); println!("the slice has {} elements", slice.len()); }
在上例中,我們獲取一個數組的切片,當我們對陣列進行切片時,我們必須在 [] 括號中提供起始和結束索引,以指定我們想要在我們的切片中包含的陣列元素。
輸出
first element of the slice: 2 the slice has 4 elements
字串的切片
fn main() { let str= String::from("Hey Tuts!!"); let hello = &str[0..5]; let hello=&str[..5]; println!("the hello contains {}", hello); }
如果我們僅想要考慮從第一個元素開始的切片,那麼我們可以避免使用第一個整數,只需在 [] 括號中鍵入結束索引。
輸出
the hello contains Hey T
範例
但是,如果我們想要從一個索引切片到字串末尾,我們可以這樣做。
fn main() { let str= String::from("Hey Tuts!!"); let hello = &str[3..]; let hello=&str[3..]; println!("the hello contains {}", hello); }
輸出
the hello contains Tuts!!
廣告