Vec
Vec 是可調整大小的標準堆積配置緩衝區:
fn main() { let mut v1 = Vec::new(); v1.push(42); println!("v1: len = {}, capacity = {}", v1.len(), v1.capacity()); let mut v2 = Vec::with_capacity(v1.len() + 1); v2.extend(v1.iter()); v2.push(9999); println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity()); // Canonical macro to initialize a vector with elements. let mut v3 = vec![0, 0, 1, 2, 3, 4]; // Retain only the even elements. v3.retain(|x| x % 2 == 0); println!("{v3:?}"); // Remove consecutive duplicates. v3.dedup(); println!("{v3:?}"); }
Vec 會實作 Deref<Target = [T]>。也就是說,您可以在 Vec 上呼叫切片方法。
This slide should take about 10 minutes.
Vecis a type of collection, along withStringandHashMap. The data it contains is stored on the heap. This means the amount of data doesn’t need to be known at compile time. It can grow or shrink at runtime.- 請留意
Vec<T>也能做為泛型型別,但您不必明確指定T。和往常的 Rust 型別推論一樣,系統會在第一次push呼叫期間建立T。 vec![...]是用於取代Vec::new()的標準巨集,且支援在向量中加入初始元素。- 如要為向量建立索引,請使用
[],但如果超出範圍會引發恐慌。或者,使用get則可傳回Option。pop函式會移除最後一個元素。 - 我們會在第 3 天談到切片。現階段,學生只需知道
Vec型別的值也能存取所有記錄下來的切片方法。