needs_drop Reports Drop Glue Needs

needs_drop tells generic code at compile time whether T runs cleanup, so arenas and containers can branch their teardown without runtime checks.

RustData Integrity

Code

rustsnippet
22 lines
use std::any::type_name;
use std::mem::needs_drop;

struct LogBuffer {
    lines: Vec<String>,
}

// 泛型代码在编译期就知道 T 是否需要清理逻辑
fn describe_slot<T>() {
    if needs_drop::<T>() {
        println!("{:>14}: needs drop glue at scope exit", type_name::<T>());
    } else {
        println!("{:>14}: plain bits, no cleanup to run", type_name::<T>());
    }
}

fn main() {
    describe_slot::<u32>();
    describe_slot::<&str>();
    describe_slot::<String>();
    describe_slot::<LogBuffer>();
}

What the code does

The working surface is the functions describe_slot and main — everything else is wiring.

Points of care

  • Nothing arrives from a registry; the language ships every API used.

Statements that matter

fn describe_slot<T>() {
    if needs_drop::<T>() {
        println!("{:>14}: needs drop glue at scope exit", type_name::<T>());
    } else {
        println!("{:>14}: plain bits, no cleanup to run", type_name::<T>());
    }
}

Interactive Tools for This Topic

FAQ

How do you run needs_drop Reports Drop Glue Needs?
This is a complete program, not a library excerpt — execution starts at the top.