Traits

Of course traits can also be generic. Here we define one which reimplements
the Drop trait as a generic method to drop itself and an input.

  1. // Non-copyable types.
  2. struct Empty;
  3. struct Null;
  4. // A trait generic over `T`.
  5. trait DoubleDrop<T> {
  6. // Define a method on the caller type which takes an
  7. // additional single parameter `T` and does nothing with it.
  8. fn double_drop(self, _: T);
  9. }
  10. // Implement `DoubleDrop<T>` for any generic parameter `T` and
  11. // caller `U`.
  12. impl<T, U> DoubleDrop<T> for U {
  13. // This method takes ownership of both passed arguments,
  14. // deallocating both.
  15. fn double_drop(self, _: T) {}
  16. }
  17. fn main() {
  18. let empty = Empty;
  19. let null = Null;
  20. // Deallocate `empty` and `null`.
  21. empty.double_drop(null);
  22. //empty;
  23. //null;
  24. // ^ TODO: Try uncommenting these lines.
  25. }

See also:

Drop, struct, and trait