What Are Dynamically Sized Types (DSTs) in Rust?

Dynamically Sized Types (DSTs) are types like slices and trait objects with sizes unknown at compile time, requiring access via pointers and the ?Sized bound.

Dynamically Sized Types (DSTs) are types whose size is not known at compile time, such as str, slices like [T], and trait objects like dyn Trait. You cannot store a DST directly on the stack; you must access it through a pointer like &T, Box<T>, or Rc<T>. When using a DST in a generic function, you must explicitly allow it by adding the ?Sized bound instead of the default Sized bound.

trait Draw {
    fn draw(&self);
}

struct Circle;
impl Draw for Circle {
    fn draw(&self) { println!("Circle"); }
}

fn render<T: Draw + ?Sized>(item: &T) {
    item.draw();
}

fn main() {
    let circle = Circle;
    render(&circle);
    render(&dyn Draw + '_);
}