Option<T> 是 Drop 的记录在哪里?

Where is it documented that Option<T> is Drop?

我希望如果我将 Box<T> 包装到 Option 中,drop 就会发挥作用。而这个程序确实输出 "dropped":

trait Foo {}

struct Bar {}

impl Foo for Bar {}

impl Drop for Bar {
    fn drop(&mut self) {
        println!("dropped")
    }
}

fn main() {
    let x = Box::new( Bar {} ) as Box<Foo>;
    let _y = Option::Some(x);
}

Playground

我检查了 Option and Drop 的文档,但找不到关于此行为的描述。我是否错过了一些编译器魔法,或者我认为它不能在其他地方实现,只能在特征声明或实现者定义中实现?

Option 如何实现 Drop 以及为什么文档中缺少它?

文档没有提到 Option<T> 实施 Drop 因为它没有实施它。

仅当您希望结构或枚举具有某些特殊行为时才需要Drop特征。如果您唯一需要的是释放内存和 运行 子元素的析构函数,编译器将自行完成。来自 Rustonomicon 中的相关页面:

If a struct has no special logic for being dropped other than dropping its children, then it means Drop doesn't need to be implemented at all!

Option 没有 Drop 实现,因为它的销毁没有涉及特殊逻辑,这与 Rc(递减引用计数器)或 MutexGuard(解锁父互斥锁)。您可以观察到与您自己的类型相同的行为,struct Thingie(Bar, Bar) 中的 Bars 将被丢弃,就像包裹在 Some.

中一样

请注意,"X has no Drop implementation" 以上的任何地方实际上都意味着没有实现 - 编译器不会隐式实现。

你也可以直接测试一个类型是否实现了Drop:

fn test_for_drop<T: Drop>() { }

fn main() {
    test_for_drop::<Option<i32>();
}

Playground

这会产生错误:

error[E0277]: the trait bound `std::option::Option<i32>: std::ops::Drop` > is not satisfied
 --> src/main.rs:4:5
  |
4 |     test_for_drop::<Option<i32>>();
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::ops::Drop` is not implemented for `std::option::Option<i32>`
  |
note: required by `test_for_drop`
 --> src/main.rs:1:1
  |
1 | fn test_for_drop<T: Drop>() {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^