ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.