Error code E0120
Drop was implemented on a trait object or reference, which is not allowed;
only structs, enums, and unions can implement Drop.
Erroneous code examples:
#![allow(unused)]
fn main() {
trait MyTrait {}
impl Drop for MyTrait {
fn drop(&mut self) {}
}
}
#![allow(unused)]
fn main() {
struct Concrete {}
impl Drop for &'_ mut Concrete {
fn drop(&mut self) {}
}
}
A workaround for traits is to create a wrapper struct with a generic type,
add a trait bound to the type, and implement Drop on the wrapper:
#![allow(unused)]
fn main() {
trait MyTrait {}
struct MyWrapper<T: MyTrait> { foo: T }
impl <T: MyTrait> Drop for MyWrapper<T> {
fn drop(&mut self) {}
}
}
Alternatively, the Drop wrapper can contain the trait object:
#![allow(unused)]
fn main() {
trait MyTrait {}
// or Box<dyn MyTrait>, if you wanted an owned trait object
struct MyWrapper<'a> { foo: &'a dyn MyTrait }
impl <'a> Drop for MyWrapper<'a> {
fn drop(&mut self) {}
}
}