I'm trying to implement additional behaviour for a generic type if its type parameters meet particular trait bounds:
struct Foo<T> {
data: T
}
impl<T> Drop for Foo<T> where T: Debug {
fn drop(&mut self) {
println!("{:?} has been deallocated", self.data);
}
}
The idea being that Foo would implement Drop if T implements Debug, while still allowing Foo to be used for types T without Debug (which simply won't implement Drop). However, this results in a compiler error:
`Drop` impl requires `T: Debug` but the struct it is implemented for does not
Is there a way to achieve this behaviour (without splitting Foo into two separate types)?
This discussion suggests that this is not possible (or at least wasn't at the time):
Apparently this is only an issue for the Drop
trait, for other traits it works just fine:
struct Foo<T> {
data: T
}
trait MyDrop {
fn drop(&mut self);
}
impl<T> MyDrop for Foo<T> where T: Debug {
fn drop(&mut self) {
println!("{:?} has been deallocated", self.data);
}
}
So I guess my real question is: Why is conditional destructor implementation different from conditional implementation of other traits?