Vec

Vec 是标准的可调整大小堆分配缓冲区:

  1. fn main() {
  2. let mut v1 = Vec::new();
  3. v1.push(42);
  4. println!("v1: len = {}, capacity = {}", v1.len(), v1.capacity());
  5. let mut v2 = Vec::with_capacity(v1.len() + 1);
  6. v2.extend(v1.iter());
  7. v2.push(9999);
  8. println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity());
  9. // Canonical macro to initialize a vector with elements.
  10. let mut v3 = vec![0, 0, 1, 2, 3, 4];
  11. // Retain only the even elements.
  12. v3.retain(|x| x % 2 == 0);
  13. println!("{v3:?}");
  14. // Remove consecutive duplicates.
  15. v3.dedup();
  16. println!("{v3:?}");
  17. }

Vec 会实现 Deref,这意味着您可以对 Vec 调用 slice 方法。

This slide should take about 10 minutes.

  • Vec is a type of collection, along with String and HashMap. 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.
  • Notice how Vec<T> is a generic type too, but you don’t have to specify T explicitly. As always with Rust type inference, the T was established during the first push call.
  • “vec![…]”是用来代替“Vec::new()”的规范化宏,它支持向矢量添加初始元素。
  • 如需将矢量编入索引,您可以使用“[’ ‘]”方法,但如果超出边界,矢量将会 panic。此外,使用“get”将返回“Option”。“pop”函数会移除最后一个元素。
  • Slices are covered on day 3. For now, students only need to know that a value of type Vec gives access to all of the documented slice methods, too.