Declaring Arrays
Part of the Fundamentals section of Coddy's Rust journey — lesson 55 of 75.
An array is a fixed-size collection where all elements must be of the same type from the start. Arrays are created using square brackets [], and the items inside the array are separated with commas.
Here is an example of how to create an array:
let numbers = [1, 2, 3, 4, 5];To check the length of the array, we can use the .len() field:
let length = numbers.len();The variable length will hold 5 because there are 5 elements in the array.
Another way to create an array using the : keyword followed by the array type and size:
let numbers: [i32; 5] = [0; 5];Creates an array of 5 integers, all initialized to 0
Challenge
EasyCreate an array called shopping_list that contains the following items: bread, eggs, milk, and butter.
Cheat sheet
Arrays are fixed-size collections where all elements must be of the same type. Create arrays using square brackets [] with comma-separated items:
let numbers = [1, 2, 3, 4, 5];Check array length using .len():
let length = numbers.len();Create arrays with type annotation and initialization:
let numbers: [i32; 5] = [0; 5]; // Creates array of 5 integers, all initialized to 0Try it yourself
fn main() {
// Create the shopping_list array here
// Don't change the code below
println!("Shopping List:");
for i in 0..shopping_list.len() {
println!("{}", shopping_list[i]);
}
}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