beginnerCompound Types
Vec Basics
Create, modify, and iterate over dynamic arrays (Vec).
Vec Basics
Create, modify, and iterate over dynamic arrays (Vec).
Difficulty
Beginner
Code
rust
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(1);
v.push(2);
v.push(3);
println!("{:?}", v);
let v2 = vec![10, 20, 30];
println!("first: {}", v2[0]);
println!("last: {:?}", v2.last());
for val in &v2 {
println!("{}", val);
}
}Explanation
This example demonstrates how to use vec basics in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the compound-types category to build a complete understanding of this topic.