Slices

Where String structs consist of an allocated place in heap memory pointing to a sequence of characters on the stack, string slices (denoted as a type with &str) are only the latter part: an ungrowable, fixed sequence of Unicode characters pushed to the stack in order.

String slices aren't the only kind of slice. Generally, slices in Rust are references to sequences of memory cells on the stack.

Vectors (explained later) are structs stored on the heap, and are mutable, but arrays in Rust are immutable sequences of stack memory:

The syntax used to define the variable arr in the above example is shorthand for defining vectors and arrays in Rust: [1;5] means an array with five elements which all equal 1.

This is one of two primary ways that arrays can be defined in Rust, with the other method involving an explicit definition of each element to be in the array (for example, the array defined above could also be defined as [1, 1, 1, 1, 1].)

Rust arrays (denoted with [T; N], where T is a primitive type and N is an unchanging size) and slices (denoted with [T] or &[T]) are so similar in data structure that all methods implemented for slices can be used on arrays.

Arrays can be iterated over with for loops, but they also implement a trait that allows for an iterator to be used on them:


    

Iterators are implemented for most, if not all, of Rust's built-in collection types, like arrays, vectors and hash maps (the latter two are further explained in the Collections chapter).

Exercise:
Add appropriate type annotations to the incorrectly typed code below: