O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

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 and slices

We've touched on arrays a couple of times. Let's look deeper.

Arrays contain a fixed number of elements of any single type. Their type is [T; n], where T is the type of the contained values and n is the size of the array. Note that vector types (covered a bit later) give you dynamically sized arrays. This must be written out explicitly every time you wish to create an array yourself. Just like any other type, an array can be either mutable or immutable.

An array can be accessed by index by using the [n] syntax after the array name, very much like in other languages. This operation will cause a panic at runtime if you try to index beyond the length of the array.

Let's have a look at the following example:

 // fixed-array-example.rs ...

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