Rust Program to Pass ArrayList as the function argument


Pass ArrayList as the function argument

Rust Programming Language


Pass ArrayList as the function argument


Problem


Rust program that passes an ArrayList as a function argument.

Input


// Define a function that takes a vector of integers as its argument and prints out each element
fn print_vec(vec: &Vec<i32>) {
    for x in vec {
        println!("{}", x);
    }
}

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

    // Call the print_vec function with the vector as its argument
    print_vec(&vec);
}{codeBox}

Output


1
2
3
4
5{codeBox}

Explanation


In this example, the print_vec function takes a vector of integers as its argument and prints out each element using a for loop. The & symbol before the vector argument indicates that we're passing a reference to the vector rather than the vector itself, which is more efficient and avoids unnecessary copying.

In the main function, we create a vector of integers and then call the print_vec function with the vector as its argument using the & symbol to pass a reference to the vector.

The print_vec function with the vector as its argument and printing out each element of the vector.



Post a Comment