Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 132 ยท Variables and Types

Arrays

Learn Rust arrays - the [T; N] type, array literals and repeat syntax, bounds-checked indexing, iteration, 2D arrays, useful methods, and how arrays differ from slices and Vec.

An array is a fixed-size row of values that all have the same type, stored next to each other in memory. Think of the days of the week, the eight squares in a chess rank, or the 256 possible values of a byte. When you know the exact count at compile time, an array is the simplest and fastest container Rust offers: no heap allocation, no pointer chasing, nothing to free.

This lesson covers how to write array types and values, how indexing works and how Rust protects you from reading outside the array, how to loop over arrays, how to build two-dimensional grids, and which methods arrays give you. It ends with a comparison to slices and Vec, so you know when to reach for each. Arrays contain values of one type; for mixed types you use a tuple.

Array types and literals

An array type is written [T; N]: the element type T, a semicolon and the length N. The length is a compile-time constant and is part of the type. A literal lists the elements in square brackets:

Rust Creating arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There are two literal forms:

  • [a, b, c] lists every element.
  • [value; N] repeats one value N times. The value is copied, so it must be Copy (or a constant). [0u8; 8] is the usual way to make a zeroed buffer.

Because the length is part of the type, [i32; 3] and [i32; 4] are different types. You cannot pass one where the other is expected, and you cannot grow or shrink an array. If the size changes at runtime, you need a Vec.

Rust The length is part of the type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops with error[E0308]: mismatched types and the note expected an array with a size of 4, found one with a size of 3. There is no conversion, because they really are different types.

An array of a type that is not Copy cannot use the repeat form with a plain value. [String::new(); 3] is rejected with error[E0277]: the trait bound `String: Copy` is not satisfied, because the compiler would need to copy a String. The fix is std::array::from_fn, which builds each element by calling a closure with its index:

Rust Building arrays with from_fn

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The [const { ... }; N] form uses an inline const block, which Rust has supported since version 1.79. Each element is a fresh constant evaluation rather than a copy. For most code, from_fn is the easier tool.

Indexing and bounds checks

You read and write an element with square brackets and a zero-based index. The index must have the type usize, the integer type that holds sizes and positions on your platform:

Rust Reading and writing elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice that temps is declared mut. Without it, temps[1] = 22.0 would not compile, just like any other variable that you try to change.

What happens when the index is too large? Rust checks every index at runtime and panics instead of reading memory that does not belong to the array. This is a key part of Rust's memory safety: C would happily read whatever bytes lie past the end.

Rust An index that is too large (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first three lines print normally. Then the program stops with index out of bounds: the len is 3 but the index is 3, and exits with code 101 (a panic, see panics). Nothing is read past the end.

When the index is a literal and the compiler can see it is wrong (data[7] on a three-element array), the program does not even compile: the lint unconditional_panic reports an error. The panic you see above only happens because the index comes from data the compiler cannot predict.

If an out-of-range index is a normal situation rather than a bug, use get, which returns an Option:

Rust Safe access with get

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

get returns Some(&value) or None, so the caller must decide what to do. Use [] when an invalid index means your program has a bug, and get when it can come from outside (user input, a file, a calculation that might overshoot).

Bounds checks cost a comparison and a branch. In practice the cost is tiny, and the optimizer removes many of them, for example in for x in &array loops where the index can never be out of range. Iterating directly instead of indexing is both safer and often faster.

Iterating over arrays

The most idiomatic way to visit every element is a for loop over the array or a reference to it. Since Rust 2021, arrays can be iterated by value, so there are three common shapes:

Rust Three ways to loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • &scores gives &i32 references: read-only access.
  • &mut scores gives &mut i32: you change elements through *s. The dereference * is explained in references and borrowing.
  • scores.iter().enumerate() pairs each element with its index; each item is a (usize, &i32) tuple, which the pattern (i, s) destructures.
  • for s in scores consumes the array and gives you the elements themselves. Since i32 is Copy, scores is still usable afterwards. For non-Copy elements such as String, the array would be moved. Iterators covers iter, iter_mut and into_iter in depth.

Avoid writing for i in 0..array.len() { array[i] ... } unless you really need the index; it is more error-prone and slower to read.

Slices: looking at part of an array

You rarely pass a whole array to a function, because its length is baked into the type. Instead you pass a slice, &[T], a reference to any number of consecutive elements. An &[i32; 5] converts to an &[i32] automatically:

Rust Functions that accept slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

One function now handles arrays of any length, parts of arrays, and also Vecs. Slices get their own lesson; for now remember the rule of thumb: take &[T] in function parameters, not &[T; N], unless the exact length matters.

Two-dimensional arrays

An array can contain arrays. A grid of 3 rows and 4 columns is [[i32; 4]; 3]: three elements, each an array of four. Read it from the outside in: the outer length comes last.

Rust A 2D grid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

grid[2][1] first picks row 2 and then column 1 of that row. Each row is stored right after the previous one in memory (row-major order), so walking row by row is cache-friendly. All the rows have the same length, which is a guarantee a Vec<Vec<T>> does not give.

Large arrays live on the stack unless you put them in a Box or a Vec. A [u8; 10_000_000] can overflow the default thread stack. For big or growing data, use a Vec.

Useful array methods

Arrays inherit all the slice methods (because they convert to slices on demand) and add a few of their own. Here are the ones you will use most:

Rust Handy methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • contains, sort, reverse, swap, first, last and many more come from slices.
  • array.map(f) consumes the array and returns a new array of the same length. This differs from the iterator map, which is lazy and needs collect.
  • A destructuring pattern [first, second, ..] takes apart an array just like a tuple. Patterns in depth covers slice patterns.
  • Arrays compare with == element by element, when the lengths match. They also implement Debug, Clone, Copy (if the element type is Copy), Hash and Default for lengths up to 32 when using Default.

Arrays of any size implement Copy when their elements do. So let b = a; on a [i32; 1000] silently copies 4 kilobytes. Pass &a when you only need to look.

Arrays, slices and Vec

[T; N] &[T] Vec<T>
Length known at compile time, part of the type at runtime at runtime, can change
Storage inline (usually stack) borrowed view heap, owned
Can grow no no yes (push)
Typical use fixed tables, buffers, small grids function parameters the default collection

A good rule: if the size is a fixed fact of the problem (12 months, 8 bits, RGB values), use an array. If the size depends on input, use a Vec. If you are writing a function that only reads a sequence, take a slice.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of [0; 5] when the zero is an i32?

    An array type is written [element type; length]. The repeat literal [0; 5] makes five copies of 0 and has the type [i32; 5].
  2. 2. What happens at runtime if you read data[10] on a three-element array and the index comes from user input?

    Rust checks every index and panics rather than reading past the end. Use get() to receive an Option instead of a panic.
  3. 3. Why is let b: [i32; 4] = [1, 2, 3]; a compile error?

    The length N is part of the type [T; N], so arrays with different lengths are different types, and there is no implicit conversion.
  4. 4. What is the best parameter type for a function that only reads a sequence of numbers and should accept arrays of any length and also Vecs?

    A slice reference &[i32] accepts arrays, parts of arrays and Vecs (through deref coercion), and it does not take ownership.
  5. 5. In let g = [[0; 4]; 3];, how many rows and columns does the grid have?

    The outer array has 3 elements, each an inner array of 4 elements. g[2][3] is the last cell.

Summary

  • [T; N] is a fixed-size array stored inline; N is part of the type and must be known at compile time.
  • Build arrays with [a, b, c], [value; N] (value must be Copy or a const) or std::array::from_fn.
  • Indices are usize and are bounds-checked at runtime: an invalid index panics. Use get for a fallible lookup.
  • Iterate with for x in &arr, &mut arr or by value; prefer iteration to indexing.
  • Pass &[T] slices to functions instead of arrays so they work with any length and with Vec.
  • 2D grids are arrays of arrays: [[T; COLS]; ROWS]. Big or growing data belongs in a Vec.

Next: String and &str Basics