O'Reilly logo

Rust Essentials by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Arrays, vectors, and slices

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required