skip to content

In Rust, if `SmsNotifier` has an inherent `channel` method and two traits also define `channel`, which does `s.channel()` call, and how do you call each?

level: middleimportance: should knowfreq 55%

answer

  1. inherent before trait
  2. Trait::method(&value)
  3. <Type as Trait>::function()
  4. E0034 and E0790

basics

~20 s

Method-call syntax picks the inherent channel, because inherent methods are searched before trait methods for the same receiver type. Notifier::channel(&s) and Billing::channel(&s) call the trait versions; a function with no self needs <SmsNotifier as Notifier>::kind().

solid answer

~40 s

For `s.channel()` rustc looks at inherent methods before trait methods for the same receiver type, so the inherent `SmsNotifier::channel` wins and no error is reported. To reach a trait's version, call it as a path with the receiver passed explicitly: `Notifier::channel(&s)` or `Billing::channel(&s)`; the receiver's type tells rustc which impl to use. If there were no inherent method, `s.channel()` would fail with E0034, `multiple applicable items in scope`, and rustc's help suggests exactly those two calls. Associated functions without `self`, such as `fn kind() -> &'static str`, give rustc nothing to infer the type from, so `Notifier::kind()` fails with E0790 and you write the fully qualified form `<SmsNotifier as Notifier>::kind()`. The general shape is `<Type as Trait>::function(receiver, args...)`.

code

rust · 31 lines
rust
trait Notifier {
    fn channel(&self) -> &'static str;
    fn kind() -> &'static str;
}

trait Billing {
    fn channel(&self) -> &'static str;
}

struct SmsNotifier;

impl SmsNotifier {
    fn channel(&self) -> &'static str { "inherent" }
}

impl Notifier for SmsNotifier {
    fn channel(&self) -> &'static str { "notifier" }
    fn kind() -> &'static str { "push" }
}

impl Billing for SmsNotifier {
    fn channel(&self) -> &'static str { "billing" }
}

fn main() {
    let s = SmsNotifier;
    println!("{}", s.channel());
    println!("{}", Notifier::channel(&s));
    println!("{}", <SmsNotifier as Billing>::channel(&s));
    println!("{}", <SmsNotifier as Notifier>::kind());
}

go deeper

for a junior

Recall that a method can be called as a path with the receiver as the first argument, such as Notifier::channel(&s).

for a middle

Explain inherent-before-trait lookup, when E0034 appears, and why an associated function without self needs <Type as Trait>::function() and E0790 otherwise.

for a senior

Point out that inherent shadowing is silent and that receiver steps can let a by-value trait method beat an inherent &self one, so ambiguous names deserve path syntax in reviews.

for a principal

Treat colliding method names across traits as an API naming problem: prefer distinct names in traits you own and reserve qualified calls for genuine collisions.

## The situation Rust lets several items with the same name apply to one type. A notification type might have: - an **inherent method**, defined in `impl SmsNotifier { fn channel(&self) ... }`; - a `channel` method from `impl Notifier for SmsNotifier`; - another `channel` method from `impl Billing for SmsNotifier`. None of these definitions is an error by itself. The question is only what happens at the **call site**, and how to name the one you want. ## What method-call syntax picks For `s.channel()`, rustc builds a list of candidate receiver types (here `SmsNotifier`, then `&SmsNotifier`, then `&mut SmsNotifier`; for a type that dereferences to another, the dereferenced types follow). For each candidate type in order, the Rust Reference says it searches: 1. the type's **inherent methods**, then 2. methods of **visible traits** implemented by the type. Because all three `channel` methods take `&self`, they are all found at the same step, `&SmsNotifier`, and the inherent one is checked first. So `s.channel()` calls the inherent method, silently, with no warning. If the inherent method did not exist, both trait methods would match at that step and rustc 1.99.1 would stop with E0034, `multiple applicable items in scope`, listing each candidate and suggesting `Billing::channel(&s)` and `Notifier::channel(&s)`. ## Naming a trait's method explicitly Every method can also be called as an ordinary function through a path. The receiver becomes the first argument: - `Notifier::channel(&s)` calls the `Notifier` implementation. rustc knows the impl from the type of `&s`. - `Billing::channel(&s)` calls the `Billing` implementation. - `SmsNotifier::channel(&s)` resolves like method-call syntax on the type: inherent first. This is often enough: whenever a method has a `self` receiver, the argument's type tells rustc which implementation to use. ## Associated functions without `self` An **associated function** has no receiver, for example a constructor or `fn kind() -> &'static str`. Writing `Notifier::kind()` gives rustc a trait but no type, so it cannot pick an impl. rustc 1.99.1 rejects it with E0790, `cannot call associated function on trait without specifying the corresponding `impl` type`, even when only one type implements the trait; its help then suggests the fix. The answer is **fully qualified syntax**: ```rust let k = <SmsNotifier as Notifier>::kind(); ``` The Rust Book gives the general form as `<Type as Trait>::function(receiver_if_method, next_arg, ...)`. You may use it everywhere, but you only need it when rustc cannot work out the type or the trait on its own. ## Choosing the call form | Call form | Picks | When it is needed | |---|---|---| | `s.channel()` | inherent first, then a unique trait method | the normal case | | `Notifier::channel(&s)` | the `Notifier` impl for the type of `&s` | two traits share a method name | | `<SmsNotifier as Billing>::channel(&s)` | exactly that type and trait | always valid; rarely required for methods | | `<SmsNotifier as Notifier>::kind()` | exactly that type and trait | associated functions with no `self` | ## Practical points - An inherent method **shadows** trait methods of the same name and receiver silently. If a reviewer sees `s.channel()` and expects the trait's behaviour, the code may be calling something else. - A trait method can still win over an inherent one when it is found at an **earlier receiver step**: a trait method taking `self` by value is checked at `SmsNotifier`, before an inherent `&self` method at `&SmsNotifier`. Path syntax removes the doubt. - The same rules apply inside generic code, but there rustc first searches the trait bounds on the type parameter, which usually makes the call unambiguous. ## Walking through the snippet The snippet below defines all three `channel` methods plus the associated function `kind`, and calls them four ways: 1. `s.channel()` prints `inherent`: all candidates take `&self`, so they meet at the same receiver step, where inherent methods are searched first. 2. `Notifier::channel(&s)` prints `notifier`: the path names the trait, and `&s` fixes the type. 3. `<SmsNotifier as Billing>::channel(&s)` prints `billing`: the fully qualified form names both the type and the trait, so nothing is left to inference. 4. `<SmsNotifier as Notifier>::kind()` prints `push`: with no receiver, this is the only form rustc accepts; the second example shows what `Notifier::kind()` produces instead. In interviews, the useful summary is short: method-call syntax resolves by receiver step and puts inherent methods first; path syntax with the receiver as the first argument picks a trait; `<Type as Trait>::` picks both and is mandatory when there is no receiver to infer from.

  • If you delete the inherent `channel`, what does `s.channel()` do with both trait impls in scope?
    It fails to compile with E0034, `multiple applicable items in scope`: both trait methods match at the same receiver step and neither has priority. rustc's help suggests `Billing::channel(&s)` and `Notifier::channel(&s)`. Removing one trait from scope at that call site would also make the call unambiguous.
  • Can a trait method ever be chosen over an inherent method with the same name by `s.channel()`?
    Yes, when the trait method is found at an earlier receiver step. rustc tries the receiver type itself before `&T` and `&mut T`, so a trait method taking `self` by value matches at `SmsNotifier` before an inherent `&self` method is considered at `&SmsNotifier`. Inherent-first applies within one step, not across steps.
  • Why does `Notifier::kind()` fail even when `SmsNotifier` is the only implementor?
    Trait paths do not select an impl by counting implementors; another crate or a later change could add one. Without a receiver there is no type to infer from, so rustc reports E0790 and asks for `<SmsNotifier as Notifier>::kind()`, which names the impl explicitly.

  • Defining two traits with the same method name on one type is a compile error.
  • Method-call syntax picks whichever trait was imported last.
  • Notifier::kind() works when only one type implements Notifier.
  • Trait methods always take priority over inherent methods of the same name.
  • Fully qualified syntax is only allowed when a call is ambiguous.