Suppose we have a bunch of alien creatures to populate a game level, then we would probably want to store their names in a handy list. Rust's array is just what we need:
// from Chapter 4/code/arrays.rs let aliens = ["Cherfer", "Fynock", "Shirack", "Zuxu"]; println!("{:?}", aliens);
To make an array, separate the different items by commas and enclose the whole thing within [ ]
(rectangular brackets). All the items must be of the same type. Such an array must be of a fixed size (this must be known at compile time) and cannot be changed; this is stored in one contiguous piece of memory.
If the items have to be modifiable, declare your array with let mut
; however, even then the number of items cannot change. The aliens array could be of the type that is annotated as [&str; 4]
where the first parameter is the type of the items and the second is their number:
let aliens: [&str; 4] = ["Cherfer", "Fynock", "Shirack", "Zuxu"];
If we want to initialize an array with...