Course contentsShow
← Rust
Lesson 727 of 1,9106. Generics and Static DispatchFree lesson

The Role of the Sized Trait

Explicitly disable the Sized requirement to support unsized types in generic interfaces.

In this lesson, you will learn how to explicitly opt out of Rust’s default Sized requirement to allow your generic functions to accept "unsized" types.

The Implicit Bound

By default, every generic type parameter in Rust carries an implicit Sized bound. When you write fn process<T>(item: T), Rust assumes T has a size known at compile time. This is why you can move item into a variable or pass it by value.

However, some types in Rust are Dynamically Sized Types (DSTs), such as slices ([T]) or trait objects (dyn Trait). Because their size is only known at runtime, they do not automatically implement the Sized trait. If you try to pass one to a generic function, the compiler will complain.

Using ?Sized

To support these types, you must explicitly tell the compiler, "I don't require this type to have a known size at compile time." We do this using the special ?Sized bound (pronounced "maybe sized").

fn print_anything<T: ?Sized>(item: &T) {
    // We can only work with references to T because 
    // T might not be Sized.
    println!("Got an item!");
}

fn main() {
    let slice: &[i32] = &[1, 2, 3];
    print_anything(slice); // This works because of ?Sized
}

Why this matters

When you add : ?Sized, you are effectively saying: "I promise not to try to put T on the stack or move it by value." Because T might be a slice or a trait object, the compiler restricts you to using T behind a pointer (like &T or Box<T>).

By opting out of the Sized trait, you make your generic code significantly more flexible, allowing it to handle both standard fixed-size types and complex, dynamically-sized types that represent the core of Rust’s powerful abstraction patterns.

Key Takeaway: The ?Sized bound allows your generic functions to accept dynamically sized types by explicitly opting out of the default requirement that all generic types must have a known size at compile time.