RRust By Example

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

Vec is a growable array. Use push to add, pop to remove.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the compound-types category to build a complete understanding of this topic.

More Compound Types Examples