Need for trait in scope to call methods

This post explains why it is necessary to have a trait in scope in order to call its methods:
https://stackoverflow.com/questions/25273816/why-do-i-need-to-import-a-trait-to-use-the-methods-it-defines-for-a-type#:~:text=In%20Rust%20a%20trait%20must,For%20example%3B%20what%20would%20object.
But I'm still a little confused. The example given is that both the std::fmt::Debug and std::fmt::Display traits define a fmt method with the same signature. It implies that a type can implement multiple versions of a method with the same signature. Is that true? If so I wonder if Rust is the only well-known programming language that allows that. Also, it seems there could be cases where both Debug and Display are in scope, so how would it know which version to invoke? Perhaps the answer is that you aren't allowed to have both in scope when calling a method defined by both.

Yes, it is.

If so I wonder if Rust is the only well-known programming language that allows that.

  • Two crates are allowed to define two traits with methods that have the same name and signature (Debug and Display are from the same crate, but they wouldn't have to be).
  • They can implement those traits for a single type in the standard library. Some people call this "principled monkey patching", unlike regular monkey patching which doesn't handle conflicts like this.
  • A third crate can depend on both of them. Rust's design does a lot of contortions to make this sort of composability work.

In order to ensure that the same type can't have multiple versions of a method with the same signature, one of those three bullet points has to go (usually, it's the principled monkey patching that's not allowed: I don't think Rust is the only language that has it, but I'm not familiar enough with Ocaml or Haskell to really speak authoritatively about their polymorphism systems).

The feature you want is fully-qualified function calls. Like this:

Debug::fmt(&object, &mut formatter)?;
Display::fmt(&object, &mut formatter)?;
3 Likes

Some examples on the playground.

2 Likes