Course contentsShow
← Rust
Lesson 277 of 1,9103. Borrowing and ReferencesFree lesson

Understanding Unsize Coercion

Leverage dynamic sizing to treat arrays as slices via references.

In this lesson, you will learn how Rust automatically transforms fixed-size arrays into flexible slices using a mechanism called "unsize coercion."

The Problem with Fixed Sizes

In Rust, an array like [i32; 3] has a known, fixed size at compile time. This is great for performance, but it can be rigid. If you have a function that needs to process a list of numbers, you don’t want to write separate versions for arrays of length 3, 4, or 100. You want a way to pass any collection of integers to the same function.

Enter the Slice

A slice (&[i32]) is a "dynamically sized" view into a sequence of data. Unlike the array, the slice does not store its length as part of its type; instead, the length is stored at runtime alongside the pointer. This is what we call a "fat pointer."

How Coercion Works

"Unsize coercion" is the magic that happens when you pass an array reference where a slice is expected. Because the compiler knows the length of your array, it can automatically "coerce" the &[i32; 3] (the array reference) into a &[i32] (the slice reference).

fn print_length(data: &[i32]) {
    println!("The slice has {} elements.", data.len());
}

fn main() {
    let my_array = [10, 20, 30];
    
    // The array is coerced into a slice automatically!
    print_length(&my_array); 
}

In the example above, &my_array is technically an &[i32; 3]. However, Rust sees that print_length demands a slice, so it quietly converts the array reference into a slice reference for you. It packs the pointer to the array and the length of the array into that "fat pointer" format, allowing the function to accept it seamlessly.

This coercion is non-breaking and happens safely at compile time. It allows your code to remain generic and flexible without you having to manually slice the array every time you want to share it with a function.

Key Takeaway: Unsize coercion allows Rust to automatically convert references to fixed-size arrays into flexible, dynamically-sized slices, enabling your functions to handle collections of varying lengths seamlessly.