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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input12Arrays Basics
Declaring ArraysArray as ParameterAccessing ElementsModifying ArraysRecap - Pretty Print Array