Rust program to pass an array into the function using call by reference mechanism

Rust | Array Example: Write a program to pass an array into the function using call by reference mechanism.
Submitted by Nidhi, on October 19, 2021

Problem Solution:

In this program, we will create an integer array with 5 values. Then we will pass created array into a user-defined function using call by reference mechanism.

Program/Source Code:

The source code to pass an array into a function using the call by reference mechanism is given below. The given program is compiled and executed successfully.

// Rust program to pass an array into function 
// using call by reference mechanism

fn ModifyArray(intArr:&mut [i32;5]){
   for i in 0..5 {
      intArr[i] = 10;
   }
   println!("Array elements inside ModifyArray() function:\n{:?}",intArr);
}

fn main() {
   let mut intArr = [1,2,3,4,5];
   
   ModifyArray(&mut intArr);

   println!("Array elements inside main() function:\n{:?}",intArr);
}

Output:

Array elements inside ModifyArray() function:
[10, 10, 10, 10, 10]
Array elements inside main() function:
[10, 10, 10, 10, 10]

Explanation:

In the above program, we created two functions ModifyArray() and main(). The ModifyArray() is a user-defined function, it accepts an array as a call by reference. Here, we modified the elements of the array and modification will also reflect in the calling function.

Here, we created an array intArr with 5 integer values. Then we passed created array in the ModifyArray() function and then print the updated array elements.

Rust Arrays Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.