Vector
A Vec struct contains a ptr to the head of the allocation in the heap, len and capacity.
ptr len capacity
+--------+--------+--------+
| 0x0123 | 2 | 4 |
+--------+--------+--------+
|
v
Heap +--------+--------+--------+--------+
| 'a' | 'b' | uninit | uninit |
+--------+--------+--------+--------+
References:
Cheatsheet
let v0 = vec![1, 2, 3];
let v1 = vec![0; 10];
let v2 = Vec::from(arr1); // arr1: [u8; 10], from array or slice
let v3: Vec<u8> = (0..10).collect();
let mut v1: Vec<i32> = (0..10).collect();
v1.push(11);
v1[10];
v1.len();
// get pop push insert
v1.iter();
Examples
Basic operations
get,set,len,push,pop,slice
test_vec.rs
#[test]
fn test_vec() {
let mut v1 = vec![1, 2, 3];
assert_eq!(v1.len(), 3);
assert_eq!(v1, Vec::from([1, 2, 3]));
assert_eq!(v1, [1, 2, 3]);
v1[0] = 7;
assert_eq!(v1[0], 7);
let mut v2: Vec<i32> = Vec::new();
v2.push(1);
v2.push(2);
v2.push(3);
assert_eq!(v2.pop(), Some(3));
match v2.get(5) {
Some(_) => println!("get key"),
None => println!("out of bound"),
}
}
Advanced operations
#[test]
fn test_advanced_vec() {
let mut vec = vec![0; 5];
assert_eq!(vec, [0, 0, 0, 0, 0]);
// extend with an iterator
vec.extend([1, 2, 3].iter().copied());
}
Questions
Differences between 'array' and 'vector'
- Array is stored in the stack.
- Array has fixed length at compile time.
- For performance, array is a little bit faster than vector. Ref
Differences between 'slice' and 'vector'
A Vec indicates ownership of the memory, and a slice indicates a borrow of memory. A Vec needs to deallocate all the items and the chunk of memory when it is itself deallocated (dropped in Rust-speak). This happens when it goes out of scope. The slice does nothing when it is dropped.