Slices and Strings

What Is a Slice?

In Rust, a slice is a primitive type[1] built into the core library. Written generically as [T], a slice is a view into a sequence of elements of type T in memory. That memory may be on the heap, on the stack, or in the read-only data section used for literals. In particular, a string slice, str, is a slice of bytes [u8] containing valid UTF-8.

UTF-8 (8-bit Unicode Transformation Format) is a variable-length character encoding defined by the Unicode standard. It can represent any Unicode character, and its single-byte encodings remain compatible with ASCII.

Slice types are unusual: you cannot declare local variables of type [T] or str unless you use a nightly compiler and enable the unsized_locals feature:

1
2
3
4
5
#![feature(unsized_locals)]
let mut s = String::from("Hello");
s.push_str(" world");
let boxed_str: Box<str> = s.into_boxed_str();
let ss: str = *boxed_str;

A [T] slice is commonly accessed in the following forms:

  • &[T]: A shared slice, an immutable borrow of a slice. It does not own the memory object [T]. A shared slice is sometimes simply called a slice.
  • &mut [T]: A mutable slice, which mutably borrows the memory object [T] it points to, also without owning it.
  • Box<[T]>: A boxed slice, a smart pointer that owns a memory object [T] stored on the heap.
  • Vec<T>: A growable dynamic array that owns a memory object [T] stored on the heap.

The same applies to str, which appears through forms such as &str, &mut str, Box<str>, and String. The first two are references to str; the latter two contain pointers to it.

1
2
3
4
5
// The difference is ownership: boxed_array owns the heap allocation; slice does not.
let boxed_array: Box<[i32]> = Box::new([1, 2, 3]); // The heap-allocated [i32; 3] array is automatically coerced to a slice [i32].

// A shared slice of the array's contents.
let slice: &[i32] = &boxed_array[..];

In some situations, [T] and str are read-only, and the compiler only lets us access them through shared references, &[T] and &str. A common example is a string literal. It is embedded in the executable and remains valid throughout the program's execution, so a reference to it can have a static lifetime. In other words, a variable bound to a string literal can have type &'static str. This does not mean every str with a 'static lifetime must be immutable: it is still possible to construct an &'static mut str.

Every element of a slice is initialized. Accessing a slice through safe Rust methods or operators automatically performs bounds checking.

Some languages, such as C, append a null character \0 to a string and keep track of its starting address. To find the string's length, the program must scan the bytes from that address until it reaches the null byte. Rust uses a different approach: an &str reference is a wide pointer containing both the string's starting address, as a raw pointer, and its length in bytes. This avoids scanning for a terminator and allows the length of literals to be determined at compile time.

In fact, all three slice pointer forms above are wide pointers. Each contains a pointer to the memory object and its size, taking up twice the space of an ordinary pointer. Why do slice references need to be wide? Because slices are dynamically sized types.

Dynamically Sized Types

Most Rust types have a fixed size known at compile time and implement the Sized trait. A type whose size is only known at runtime is called a dynamically sized type (DST), or informally, an unsized type. Slices and trait objects are two examples.

The unknown size belongs to the type, not to a particular value. For example, str can have any length within the limits of the hardware, but a particular string literal such as "Hello World!" has a definite, unchanging length known at compile time.

A reference to a sized type only needs to point to the first byte of its memory object. It does not need to carry the object's size, because Rust generates machine code with enough type information to determine that size at compile time. For a dynamically sized type, however, knowing the type, such as str, does not tell us the extent of the referenced memory. A wide pointer is therefore necessary.

The compiler must calculate how much memory local variables require and allocate space in each stack frame accordingly. The slice syntax [1..4] selects part of the memory object belonging to a. Because the compiler cannot determine the resulting slice type's size from this syntax, the following code fails:

1
2
3
4
5
fn slice_out_of_array() {
    let a: [u8; 5] = [1, 2, 3, 4, 5];
    let nice_slice: [u8] = a[1..4]; // Error: [u8] doesn't have a size known at compile-time.
    assert_eq!([2, 3, 4], nice_slice)
}

This is why Rust does not allow local variables of type [T] or str.

The String Type

As discussed above, Rust's str consists of [u8] data that conforms to UTF-8. Similarly, String wraps a Vec<u8> and follows the same heap allocation strategy: 2 -> 4 -> 8, doubling the previous allocation when capacity runs out. Like Vec<u8>, a String stores its data on the heap and owns that allocation.

The standard library defines String as follows:

1
2
3
pub struct String {
    vec: Vec<u8>,
}

The vec field is private, so we cannot construct a string instance directly and must use the provided methods. This matters because not every sequence of [u8] bytes is valid UTF-8: directly manipulating the underlying bytes could invalidate the string. Controlled access ensures that String data remains valid. Here are two ways to initialize a String:

1
2
3
4
5
6
7
8
fn main() {
    let hello_world: &str = "hello world"; // hello_world points to read-only data.

    let s: String = String::from("hello");
    let s: String = hello_world.to_string(); // This shadows the previous variable.

    let world: &str = &s[6..]; // world points to the heap.
}

The stack representation of String has three parts: a pointer, a length, and a capacity. Compared with &str, it adds only the capacity field. Because String points to heap memory, its length can change dynamically at runtime.

String and string slice pointers※ The variable s has type String; the variable world has type &str.

An &str can point to the stack as well as to the heap or read-only data:

1
2
3
4
use std::str;

let x: &[u8] = &[b'a', b'b', b'c']; // &[u8; 3] is implicitly coerced to &[u8].
let stack_str: &str = str::from_utf8(x).unwrap(); // Convert &[u8] to &str.

Convert a stack-allocated byte array to &str, and the underlying str is naturally a memory object on the stack.

Box<str>

1
2
3
4
fn main() {
    let _s1: Box<str> = "hello".into();
    let _s2: Box<&str> = Box::new("hello world");
}

Box<str> is a special case of the boxed slices discussed above. It is a smart, wide pointer to a str stored on the heap. Unlike &str and &mut str, Box<str> owns the memory object. Compared with String, it lacks a capacity field: you cannot change the length of the str inside a Box<str>, although you can modify its contents while preserving that length and valid UTF-8.

Implicit Coercions to &str

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn main() {
    let s1: Box<str> = "hello".into();
    print_str(&s1);
    let s2: String = "world".into();
    print_str(&s2);
}

fn print_str(s: &str) {
    println!("{}", s);
}

Here, &s1 and &s2 refer to the stack representations of s1 and s2, rather than directly to the heap allocations. Rust allows &String and &Box<str> to coerce implicitly to &str, but not the reverse. A function taking &str can therefore accept not only an &str, but also an &String or &Box<str>, making the interface more flexible.

Slice Syntax

Rust's slice syntax [x..y] selects a contiguous sequence of values of the same type from memory. The range x..y has the mathematical meaning [x, y): it includes x and excludes y. Either operand of .. can be omitted:

  • ..y is equivalent to 0..y.
  • x.. extends from position x to the end.
  • .. extends from position 0 to the end.

A slice cannot be bound directly to a local variable, so the slice expression [x..y] must be preceded by & to obtain a reference to it. With automatic dereferencing, slice syntax can be used with types such as str, [T], [T; N], String, Vec<T>, Box<str>, and Box<T>, as well as references to them.

Be particularly careful when slicing strings: indices must fall on UTF-8 character boundaries. A Chinese character, for example, commonly occupies three bytes in UTF-8. Taking only the first two bytes of such a string would cut its first character in half, causing the program to panic.

Summary

Memory objects of type [T] or str can live in three places:

  • On the stack, as described above.
  • On the heap, through types such as Box<T> and String.
  • In read-only data: string literals such as "hello" are embedded directly in the executable and loaded into the read-only data section at runtime.

The following diagram brings together the memory layouts of Rust strings:

Memory layouts of Rust strings

Refresh