← 中文资源

简体中文版本

needs_drop 泛型清理分支

needs_drop 在编译期告知泛型代码 T 是否携带 Drop 清理:u32 与引用无清理逻辑,String 等拥有资源的类型需要,容器可据此跳过运行期判断。

阅读英文原文

实现说明

活动部件是函数 describe_slot、main。

常见问题

「needs_drop 泛型清理分支」这个示例怎么运行?

运行这个文件就行;脚本没有任何外部要求。

核心语句

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>());
    }
}

代码示例

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>();
}