In this lesson, you will learn how Rust decides which method to call when both an inherent implementation and a trait implementation provide a method with the same name.
The Method Resolution Hierarchy
In Rust, "coherence" ensures that there is always a clear, unambiguous way to resolve method calls. When you call a method on a type—like my_instance.do_something()—the compiler follows a specific order of precedence to find the implementation.
Inherent vs. Trait Methods
The fundamental rule is that inherent methods always take precedence over trait methods.
An inherent method is one defined directly on a type using an impl block (e.g., impl MyStruct { ... }). A trait method comes from a trait you have implemented for that type. If you define a method with the same name in both places, Rust will choose the inherent version every time.
Consider this example:
struct Robot;
trait Greeter {
fn say_hello(&self) { println!("Hello from Trait!"); }
}
impl Greeter for Robot {}
impl Robot {
// This inherent method hides the trait method
fn say_hello(&self) { println!("Hello from Inherent!"); }
}
fn main() {
let r = Robot;
r.say_hello(); // Output: "Hello from Inherent!"
}
Why does this matter?
This rule provides stability. Because you own the type, the inherent method is considered the "primary" definition. If a third-party library adds a new trait method that happens to share a name with a method you’ve already written for your type, your code won't suddenly break or change behavior. Your local definition remains the source of truth.
If you ever find yourself in a situation where you actually want to use the trait method instead of your inherent one, you can bypass this resolution rule by using "fully qualified syntax." Instead of r.say_hello(), you would call <Robot as Greeter>::say_hello(&r). This explicitly tells the compiler to ignore the inherent method and look directly at the trait implementation.
Key Takeaway: When a method name exists in both an inherent implementation and a trait, Rust will always prioritize the inherent method to ensure predictable and stable behavior.