?Sized Bounds Accept dyn And str

The ?Sized bound relaxes the implicit Sized constraint, letting generic functions accept &str and &dyn Trait references alongside ordinary types.

RustData Integrity

Code

rustsnippet
25 lines
use std::fmt::Display;

// 默认泛型参数隐含 Sized;?Sized 放开后 str、dyn Trait 也能以引用传入
fn describe<T: ?Sized + Display>(item: &T) -> String {
    format!("value is {item}")
}

fn main() {
    // 普通 Sized 类型
    let n = 42;
    println!("{}", describe(&n));

    // str 本身没有大小:只有 &str、Box<str> 这类指针能承载它
    println!("{}", describe("hello"));

    // dyn Display 同样 unsized:trait 对象引用走同一条路
    let boxed: Box<dyn Display> = Box::new(3.5);
    println!("{}", describe(&*boxed));

    // 对照:不带 ?Sized 的版本只接受 Sized 类型
    fn sized_only<T: Display>(item: &T) -> String {
        format!("sized {item}")
    }
    println!("{}", sized_only(&n));
}

The code in one pass

The code’s whole job belongs to the functions describe, main and sized_only.

What to watch for

  • The dependency list is empty; the runtime itself covers it all.

Putting it to use

main is the driver: it invokes describe and sized_only before returning.

Core lines

let boxed: Box<dyn Display> = Box::new(3.5);
fn describe<T: ?Sized + Display>(item: &T) -> String {
    format!("value is {item}")
}
fn sized_only<T: Display>(item: &T) -> String {
    format!("sized {item}")
}

Interactive Tools for This Topic

FAQ

How do you run ?Sized Bounds Accept dyn And str?
Direct execution is enough; the script has no external requirements.