array as a parameter rust
In Rust, you can pass an array as a parameter to a function. To do this, you need to specify the type of the array and its size in the function signature.
Here's an example of how you can pass an array as a parameter in Rust:
fn print_array(arr: &[i32; 5]) {
for element in arr.iter() {
println!("{}", element);
}
}
fn main() {
let my_array = [1, 2, 3, 4, 5];
print_array(&my_array);
}
In this example, we define a function called print_array
that takes an array of type [i32; 5]
as a parameter. The &
symbol before my_array
in the print_array
function call is used to pass a reference to the array instead of its ownership.
Inside the print_array
function, we iterate over the elements of the array using the iter
method and print each element.
In the main
function, we declare an array called my_array
with elements [1, 2, 3, 4, 5]
. We then call the print_array
function and pass a reference to my_array
as the argument.
When you run this code, it will output each element of the array on a new line.
Note that in Rust, when you pass an array as a parameter, the size of the array is part of its type. This means that if you want to pass arrays of different sizes to the same function, you need to define multiple versions of the function with different array types.
I hope this helps! Let me know if you have any further questions.