trait-concept

Rust Using ?Sized with trait bounds

Generic type parameters normally require Sized. Relax that implicit requirement using ?Sized when a function only needs a reference and can work with an unsized type such as dyn Trait or str. This does not require the type to be unsized. Expected output (not executed): text 42 7 Why: The reference is sized even when its referent is not. All three referents support Display. Common mistake: Interpreting ?Sized as a requirement to be dynamically sized.

Formal Syntax & Structure

rust syntaxrust
fn show<T: Trait + ?Sized>(item: &T)

Working Example

Example Snippetrust
use std::fmt::Display;fn show<T: Display + ?Sized>(item: &T) { println!("{item}"); }fn main() {    show("text");    show(&42);    let item: &dyn Display = &7;    show(item);}
Rust Reference