Passing Arrays as Parameters to Functions
We can pass an array as a parameter either by a call by value or call by reference to a function.
Example 1: Pass by value
Rust
fn main() { let gfg_array = [1,2,3,4]; change_array(gfg_array); print!( "Original array {:?}" ,gfg_array); } fn change_array( mut gfg_array:[i32;4]){ for i in 0..4 { gfg_array[i] = 0; } println!( "Changed array {:?}" ,gfg_array); } |
Output:
Changed array [0, 0, 0, 0]
Original array [1, 2, 3, 4]
Example 2: Pass by reference
Rust
#![allow(unused)] fn main() { let mut gfg_array = [1,2,3,4,5]; change_array(& mut gfg_array); print!( "Original array {:?}" ,gfg_array); } fn change_array(gfg_array:& mut [i32;5]){ for i in 0..5 { gfg_array[i] = 0; } println!( "Changed array {:?}" ,gfg_array); } |
Output:
Changed array [0, 0, 0, 0, 0]
Original array [0, 0, 0, 0, 0]
Rust – Array
An Array in Rust programming is a fixed-sized collection of elements denoted by [T; N] where T is the element type and N is the compile-time constant size of the array.
We can create an array in 2 different ways:
- Simply a list with each element [a, b, c].
- Repeat expression [N, X]. This will create an array with N copies of X.
[X,0] It is allowed but can cause some hectic problems so if you are using this type of expression be mindful of side effects. Array size from 0-32 implements the default trait if allowed by its type. Trait implementations are up to 32 sizes. An array is not iterateable itself.
Syntax:
ArrayType : [ Type ; Expression]
An array is written as:
let array: [i32; 3] = [4, 5, 6];
Contact Us