Vectors
Create and push
Vec<T> owns a heap-allocated list.
let mut nums = Vec::new();
nums.push(10);
nums.push(20);
println!("{:?}", nums);
Use a macro literal
vec! builds a vector quickly.
let nums = vec![1, 2, 3];
println!("{}", nums[1]);
Iterate
Borrow elements with a for loop.
for n in &nums {
println!("{n}");
}
Vector safety
- Indexing past the end panics
- Prefer
.get(i)which returnsOption - Ownership moves out of a vector unless you clone or copy
- Store references only when lifetimes allow
Comments
One comment per signed-in account. Comments are saved with this page’s URL.