Rust Program to Iterate over ArrayList using Lambda Expression


Iterate over ArrayList using Lambda Expression

Rust Programming Language


Iterate over ArrayList using Lambda Expression


Problem


Rust program that iterates over an ArrayList using a lambda expression.

Input


fn main() {
    // Create a vector of integers
    let vec = vec![1, 2, 3, 4, 5];

    // Use a closure to iterate over the vector and print out each element
    vec.iter().for_each(|&x| println!("{}", x));
}{codeBox}

Output


1
2
3
4
5{codeBox}

Explanation


In this example, the vec variable is a vector of integers that we want to iterate over. We use the iter method to get an iterator over the elements of the vector, and then we use the for_each method to apply a closure to each element of the iterator. The closure takes a reference to each element of the iterator (which we've named x), dereferences it to get the actual value, and then prints it out to the console using println!.

The result of iterating over the elements of the vector and printing out each element using the closure.


Post a Comment