实现说明
活动部件是函数 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>();
}