Rust program to pass an array in a function

Rust | Function Example: Write an example to demonstrate the pass an array in a function.
Submitted by Nidhi, on October 06, 2021

Problem Solution:

In this program, we will create a user-defined function PrintArray() to accept an array as an argument and print array elements.

Program/Source Code:

The source code to pass an array in a function is given below. The given program is compiled and executed successfully.

// Rust program to pass an array in a function fn PrintArray(arr: &mut [i32]) { println!("Array Elements: "); for i in 0..5 { println!("{0} ", arr[i]); } } fn main() { let mut arr:[i32;5] = [10,20,30,40,50]; PrintArray(&mut arr); }

Output:

Array Elements: 
10 
20 
30 
40 
50

Explanation:

In the above program, we created two functions PrintArray() and main(). The PrintArray() function is a user-defined function that accepts an array of integers and array elements on the console screen.

In the main() function, we created an array of integers with 5 elements. Then we called PrintArray() function and printed the array elements.

Rust Functions Programs »





Comments and Discussions!

Load comments ↻





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