So far, each variable we've used holds just one piece of data, like a single number or string.
But what if you need to store multiple related items together, like all the names in a class or items on a shopping list?
Engagement Message
How might you group related values?
Rust provides a way to store an ordered collection of items: an array.
You create arrays using square brackets []
, with items separated by commas. For example: [1, 2, 3]
.
Engagement Message
What punctuation separates items inside an array?
A critical rule in Rust is that arrays are homogeneous, meaning all elements must be of the same data type. You can have an array of integers or an array of strings, but not a mix.
Example:
let my_stuff = [10, 20, 30];
is valid.
Engagement Message
Can a Rust array contain both the number 50
and the string "score"
?
Just like other data types, you assign a list to a variable using let
. Rust often infers the type, but the full syntax is let name: [Type; Length]
.
let high_scores = [1050, 980, 955];
