Menu
Coddy logo textTech

Array as Parameter

Part of the Fundamentals section of Coddy's Rust journey — lesson 56 of 75.

In Rust, you can accept arrays as parameters in the following way:

Fixed-size arrays:

fn process_array(arr: [i32; 5]) {}

This allows you to pass only arrays with the length 5 because of the 5 in [i32; 5].

Array reference using the & sign:

fn process_array(arr: &[i32]) {}

A reference is like a pointer to data instead of the data itself. Using & creates a reference. This allows to pass array of any size.

Use fixed-size arrays ([i32; 5]) when you need to work with arrays of a specific size only.

Use array references (&[i32]) when you want more flexibility - it can accept arrays of any size, and it's more memory efficient.

For example here is how to call a function that accepts a reference array:

let numbers = [1, 2, 3, 4, 5];
process_array(&numbers);

Cheat sheet

Arrays can be passed as function parameters in two ways:

Fixed-size arrays:

fn process_array(arr: [i32; 5]) {}

Only accepts arrays with exactly 5 elements.

Array references:

fn process_array(arr: &[i32]) {}

Accepts arrays of any size. More flexible and memory efficient.

Calling with array reference:

let numbers = [1, 2, 3, 4, 5];
process_array(&numbers);

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals