std::slice
最後更新
切片
&[T] 的方法:走訪、分段、切割、搜尋、排序與合併,Vec 與陣列都能共用。這個模組做什麼
切片(slice)是「一段連續元素的借用視窗」:它不擁有資料,只記錄起點與長度,指向某個陣列、
Vec 或其他連續記憶體。寫成 &[T](唯讀)或 &mut [T](可修改)。為什麼需要切片?寫函式時,參數用
&[T] 就能同時接受陣列、Vec 和其中的一段,不必為每種容器各寫一個版本。| 來源 | 轉成切片 |
|---|---|
陣列 [i32; 4] | &arr 或 &arr[1..3] |
Vec<i32> | &v、v.as_slice() 或 &v[..2] |
| 單一值 | std::slice::from_ref(&x) |
本頁方法
Vec(見 std::vec)與陣列(見 std::array)都能直接呼叫。字串切片 &str 是另一種型別,見 std::str。匯入
切片是原始型別,方法不需要
use。模組層級的函式與迭代器型別才需要:- use std::slice;
- use std::slice::{Chunks, Iter, Windows};
常用 API
切片語法與 len、is_empty
用範圍
a..b 取出一段切片,..b 從頭開始、a.. 到尾端、.. 是全部。函式參數寫 &[T],呼叫端傳 &vec 或 &array 都可以。簽名:
- pub const fn len(&self) -> usize
- pub const fn is_empty(&self) -> bool
- pub const fn first(&self) -> Option<&T>
範例:
- fn sum(values: &[i32]) -> i32 {
- values.iter().sum()
- }
- fn main() {
- let arr = [10, 20, 30, 40, 50];
- let v = vec![1, 2, 3];
- println!("{:?} {:?} {:?}", &arr[1..3], &arr[..2], &arr[3..]);
- println!("sum(arr) = {}", sum(&arr));
- println!("sum(v) = {}", sum(&v));
- println!("sum(中間) = {}", sum(&arr[1..4]));
- let empty: &[i32] = &[];
- println!("len {}, is_empty {}, first {:?}", empty.len(), empty.is_empty(), empty.first());
- }
輸出:
- [20, 30] [10, 20] [40, 50]
- sum(arr) = 150
- sum(v) = 6
- sum(中間) = 90
- len 0, is_empty true, first None
注意:範圍超出長度或起點大於終點(如
&arr[3..10])會 panic;不確定時用 arr.get(3..10),越界回傳 None。iter 與 iter_mut:走訪元素
iter() 逐一借出 &T,iter_mut() 逐一借出 &mut T 讓你就地修改。for x in &v 就是 v.iter() 的簡寫。迭代器可串接 map、filter 等轉接器,見 std::iter。簽名:
- pub fn iter(&self) -> Iter<'_, T>
- pub fn iter_mut(&mut self) -> IterMut<'_, T>
範例:
- fn main() {
- let mut prices = [100, 250, 80];
- for p in prices.iter_mut() {
- *p = *p * 9 / 10;
- }
- println!("打九折:{:?}", prices);
- let expensive: Vec<&i32> = prices.iter().filter(|&&p| p > 100).collect();
- println!("超過 100:{:?}", expensive);
- for (i, p) in prices.iter().enumerate() {
- println!("#{} {}", i, p);
- }
- }
輸出:
- 打九折:[90, 225, 72]
- 超過 100:[225]
- #0 90
- #1 225
- #2 72
windows 與 chunks:分段處理
windows(n) 產生長度 n、每次往後移一格的重疊視窗,適合計算移動平均或比較相鄰元素。chunks(n) 切成不重疊的 n 個一組,最後一組可能較短;chunks_exact 則會把不足的尾巴留在 remainder()。簽名:
- pub fn windows(&self, size: usize) -> Windows<'_, T>
- pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>
- pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>
範例:
- fn main() {
- let temps = [20, 22, 25, 24, 28];
- for w in temps.windows(2) {
- println!("{} -> {}:{:+}", w[0], w[1], w[1] - w[0]);
- }
- let avg3: Vec<i32> = temps.windows(3).map(|w| w.iter().sum::<i32>() / 3).collect();
- println!("三日平均:{:?}", avg3);
- let data = [1, 2, 3, 4, 5, 6, 7];
- let groups: Vec<&[i32]> = data.chunks(3).collect();
- println!("chunks(3):{:?}", groups);
- let exact = data.chunks_exact(3);
- println!("剩餘:{:?}", exact.remainder());
- }
輸出:
- 20 -> 22:+2
- 22 -> 25:+3
- 25 -> 24:-1
- 24 -> 28:+4
- 三日平均:[22, 23, 25]
- chunks(3):[[1, 2, 3], [4, 5, 6], [7]]
- 剩餘:[7]
注意:
windows(0) 與 chunks(0) 會 panic。split_at 與 split_first:切成兩半
split_at(mid) 在位置 mid 切成兩個切片 (&[..mid], &[mid..])。split_at_mut 給出兩個可變切片,借用檢查器允許同時修改兩邊,因為它們不重疊。split_first/split_last 拆出頭或尾一個元素與其餘部分,空切片時回傳 None。簽名:
- pub const fn split_at(&self, mid: usize) -> (&[T], &[T])
- pub const fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
- pub const fn split_first(&self) -> Option<(&T, &[T])>
範例:
- fn main() {
- let nums = [1, 2, 3, 4, 5, 6];
- let (left, right) = nums.split_at(2);
- println!("{:?} | {:?}", left, right);
- let mut board = [0; 6];
- let (a, b) = board.split_at_mut(3);
- a[0] = 1;
- b[0] = 2;
- println!("{:?}", board);
- if let Some((head, tail)) = nums.split_first() {
- println!("頭 {},其餘 {:?}", head, tail);
- }
- let parts: Vec<&[i32]> = [1, 0, 2, 3, 0, 4].split(|&x| x == 0).collect();
- println!("依 0 切開:{:?}", parts);
- }
輸出:
- [1, 2] | [3, 4, 5, 6]
- [1, 0, 0, 2, 0, 0]
- 頭 1,其餘 [2, 3, 4, 5, 6]
- 依 0 切開:[[1], [2, 3], [4]]
注意:
split_at 的 mid 大於長度會 panic;Rust 1.80 起可用 split_at_checked 取得 Option。contains、starts_with、iter().position:搜尋
contains 線性搜尋是否有某值;starts_with/ends_with 比對開頭或結尾的一段;要知道位置用 iter().position。簽名:
- pub fn contains(&self, x: &T) -> bool where T: PartialEq
- pub fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq
- pub fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq
範例:
- fn main() {
- let allowed = ["admin", "editor", "viewer"];
- println!("{}", allowed.contains(&"editor"));
- println!("{}", allowed.contains(&"guest"));
- let header: &[u8] = b"\x89PNG\r\n\x1a\n...";
- println!("是 PNG:{}", header.starts_with(b"\x89PNG"));
- println!("{}", [1, 2, 3, 4].ends_with(&[3, 4]));
- println!("{:?}", allowed.iter().position(|&r| r == "viewer"));
- }
輸出:
- true
- false
- 是 PNG:true
- true
- Some(2)
sort_unstable 與 binary_search:排序後快速查找
sort_unstable 不保證相等元素的原始順序,但通常比 sort 快且不需要額外記憶體,排序整數等「相等即完全相同」的資料時是首選。排序好的切片可以用 binary_search 以 O(log n) 查找:找到回傳 Ok(位置),找不到回傳 Err(應插入的位置)。簽名:
- pub fn sort_unstable(&mut self) where T: Ord
- pub fn sort_unstable_by_key<K: Ord, F: FnMut(&T) -> K>(&mut self, f: F)
- pub fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord
範例:
- fn main() {
- let mut ids = [42, 7, 19, 3, 88, 25];
- ids.sort_unstable();
- println!("{:?}", ids);
- println!("找 19:{:?}", ids.binary_search(&19));
- println!("找 20:{:?}", ids.binary_search(&20));
- let mut v = ids.to_vec();
- if let Err(pos) = v.binary_search(&20) {
- v.insert(pos, 20);
- }
- println!("插入後:{:?}", v);
- let mut words = ["banana", "fig", "apple"];
- words.sort_unstable_by_key(|w| w.len());
- println!("{:?}", words);
- }
輸出:
- [3, 7, 19, 25, 42, 88]
- 找 19:Ok(2)
- 找 20:Err(3)
- 插入後:[3, 7, 19, 20, 25, 42, 88]
- ["fig", "apple", "banana"]
注意:
binary_search 只在切片已排序時有意義;未排序時結果不可靠(但不會 panic)。concat 與 join:把多段合併
concat 把「切片的切片」接成一個 Vec;join(sep) 在每段之間插入分隔元素。對 &[&str] 使用時則產生 String,是組合字串清單最簡單的方式。簽名:
- pub fn concat<Item: ?Sized>(&self) -> <Self as Concat<Item>>::Output
- pub fn join<Separator>(&self, sep: Separator) -> <Self as Join<Separator>>::Output
範例:
- fn main() {
- let parts = [vec![1, 2], vec![3], vec![4, 5]];
- println!("{:?}", parts.concat());
- println!("{:?}", parts.join(&0));
- let words = ["Rust", "實戰", "秘笈"];
- println!("{}", words.concat());
- println!("{}", words.join(" / "));
- let path = ["usr", "local", "bin"].join("/");
- println!("/{}", path);
- }
輸出:
- [1, 2, 3, 4, 5]
- [1, 2, 0, 3, 0, 4, 5]
- Rust實戰秘笈
- Rust / 實戰 / 秘笈
- /usr/local/bin
to_vec、reverse、swap、fill:其他常用操作
to_vec 把切片複製成新的 Vec;reverse 原地反轉;swap(i, j) 交換兩個位置;fill 把所有元素設為同一個值;iter().max() 找最大值。簽名:
- pub fn to_vec(&self) -> Vec<T> where T: Clone
- pub const fn reverse(&mut self)
- pub const fn swap(&mut self, a: usize, b: usize)
- pub fn fill(&mut self, value: T) where T: Clone
範例:
- fn main() {
- let mut a = [1, 2, 3, 4, 5];
- let copy = a[1..4].to_vec();
- a.reverse();
- println!("{:?},copy = {:?}", a, copy);
- a.swap(0, 4);
- println!("{:?}", a);
- println!("max = {:?}", a.iter().max());
- a[..2].fill(0);
- println!("{:?}", a);
- }
輸出:
- [5, 4, 3, 2, 1],copy = [2, 3, 4]
- [1, 4, 3, 2, 5]
- max = Some(5)
- [0, 0, 3, 2, 5]
重點整理
- 切片
&[T]是借用的一段連續元素,函式參數用它可同時接受陣列與Vec - 範圍越界會 panic,用
get(range)取得Option windows重疊、chunks不重疊;split_at_mut可同時修改兩半- 已排序資料用
binary_search,Err會告訴你插入位置 sort_unstable較快;需要保留相等元素順序時改用sortconcat/join合併多段,對字串清單會得到String