liveBook · Manning

Array

As explained in Code Like a Pro in Rust

An array is a sequence data structure whose elements share a type and can be iterated over and sliced.

A Rust array is a fixed-length sequence of values of one type. Its length is known at compile time, unlike a slice’s length, which can be determined at run time. Use an array when the sequence length is fixed; borrow it as a slice when an operation should work with a length determined at run time. section 4.2

Listing 4.2 Creating an array and a slice
let array = [0u8; 64];        #1
 let slice: &[u8] = &array;   #2

The listing initializes 64 zero-valued bytes with `[0u8; 64]`, then borrows the array as `&[u8]`. The slice provides a sequence view without making the array’s fixed length part of the slice type. section 4.2

Length matters when designing interfaces: an array length must be available to the compiler and represented in the type signature. Since Rust 1.51, const generics permit generic arrays with lengths chosen at compile time, not at run time. For work on parts of a sequence, a slice can be split into nonoverlapping subslices, as with `split_at(32)`. section 4.2

How Code Like a Pro in Rust covers it

How deep it goes
Defines the length distinction and shows borrowing an array as a slice; defers detailed treatment of const generics.
Examples
Demonstrates a 64-byte zero-initialized array, its borrowed slice, and splitting that slice at element 32.
What it assumes
Assumes familiarity with Rust declarations and references; introduces the array–slice length distinction directly.
What you can do after
Practice/perform fixed-length array initialization and borrowing as a slice, while accounting for compile-time length requirements.
How it connects
Connects arrays to slices, multidimensional sequences, const generics, and divide-and-conquer algorithms.

Also explained in

Compare how 40 books explain array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.