Rust Program to Iterate over an Vec


Iterate over an Vec

Rust Programming Language


Iterate over an Vec


Problem


Rust program that iterates over a Vec.

Input


fn main() {
    let list = vec![1, 2, 3, 4, 5];
    
    println!("List: {:?}", list);
    
    for item in &list {
        println!("{}", item);
    }
}{codeBox}

Output


List: [1, 2, 3, 4, 5]
1
2
3
4
5{codeBox}

Explanation


In this example, we create a Vec<i32> called list using Rust's vec! macro.

We then print the contents of the list using println!("List: {:?}", list);.

Finally, we iterate over the list using a for loop and print each item using println!("{}", item);. Note that we use a reference to the list (&list) in the for loop to avoid taking ownership of the list.

This shows the contents of the list, followed by each item printed on a separate line in the order they appear in the list.


Post a Comment