skip to content

Methods and Receivers

Structs hold data and impl blocks attach methods whose receiver, self, &self or &mut self, says what the call may do. Interviewers ask which receiver fits and why.

on this pageshow

questions

5

In Rust, how does an associated function such as `Thermostat::new` differ from a method, and how do you declare and use an associated const?

level: juniorimportance: must knowfreq 70%

answer

  1. is there a self parameter
  2. path call versus dot call
  3. Self as the impl's alias
  4. Self::NAME, not the bare name
  5. E0599 says associated function

basics

~20 s

An associated function has no self parameter, so it is called by path, Thermostat::new(18.5). A method has a self receiver and is called with a dot. An associated const sits in the impl block and is read as Self::MAX.

solid answer

~40 s

Everything in an `impl` block is an associated item. A function whose first parameter is not `self` is an **associated function**: it belongs to the type's namespace, is called as `Thermostat::new(18.5)`, and typically constructs a value, returning `Self`. A function with a `self` receiver is a **method**; it can be called as `t.reading()` or by path as `Thermostat::reading(&t)`. Calling an associated function with a dot fails with E0599, "this is an associated function, not a method". An **associated const**, `const MAX_TARGET: f64 = 30.0;`, is written inside the impl and read as `Self::MAX_TARGET` inside it or `Thermostat::MAX_TARGET` outside; a bare `MAX_TARGET` is E0425. A type may have several impl blocks, all in the crate that defines it.

code

rust · 30 lines
rust
struct Thermostat {
    target: f64,
    current: f64,
}

impl Thermostat {
    const MIN_TARGET: f64 = 5.0;
    const MAX_TARGET: f64 = 30.0;

    fn new(current: f64) -> Self {
        Self { target: 20.0, current }
    }

    fn set_target(&mut self, target: f64) {
        self.target = target.clamp(Self::MIN_TARGET, Self::MAX_TARGET);
    }
}

impl Thermostat {
    fn reading(&self) -> f64 {
        self.current
    }
}

fn main() {
    let mut t = Thermostat::new(18.5);      // associated function: path call
    t.set_target(42.0);                     // method: dot call
    Thermostat::set_target(&mut t, 42.0);   // the same method as a path call
    println!("target {} reading {} max {}", t.target, t.reading(), Thermostat::MAX_TARGET);
}

go deeper

for a junior

Recall the difference in one line: no self means a path call such as Thermostat::new; a self receiver means a method called with a dot.

for a middle

Explain Self as an alias, path calls for methods, reading consts through Self::, and the E0599 and E0425 messages a wrong call produces.

for a senior

Discuss where associated consts beat module consts, that they are evaluated only when referenced, and the same-crate rule behind E0116 that pushes you toward a newtype.

for a principal

Frame impl blocks as how a type presents its API: a few named constructors and consts with domain meaning make a type self-describing for the teams that consume it.

## Associated items: what an impl block holds An **inherent implementation**, `impl Thermostat { .. }`, attaches items to a type. The Reference says inherent impls can contain **associated functions** (including methods) and **associated constants**. Inside the block, `Self` is an alias for the implementing type, so `fn new(current: f64) -> Self` and `Self { target: 20.0, current }` mean the same as spelling out `Thermostat`. | Item | Declared as | Called or read as | |---|---|---| | associated function | `fn new(current: f64) -> Self` | `Thermostat::new(18.5)` | | method | `fn reading(&self) -> f64` | `t.reading()` or `Thermostat::reading(&t)` | | associated const | `const MAX_TARGET: f64 = 30.0;` | `Self::MAX_TARGET`, `Thermostat::MAX_TARGET` | ## Associated functions versus methods The only structural difference is the first parameter. A method's first parameter is named `self`; that is what lets it be called with the dot operator. Every method is also an associated function, so a path call works for both: - `Thermostat::new(18.5)` calls an associated function. There is no value yet, so there is nothing to put before a dot. - `t.set_target(42.0)` and `Thermostat::set_target(&mut t, 42.0)` are the same call; the path form passes the receiver explicitly. - `t.new(19.0)` is rejected with **E0599**: "no method named `new` found for struct `Thermostat` in the current scope", labelled "this is an associated function, not a method", with a help line suggesting `Thermostat::new(19.0)`. `new` is a naming convention, not a keyword: Rust has no constructors, and any associated function returning `Self` can build a value (`with_target`, `from_reading`). How `new` divides work with `Default` and fallible constructors is covered with the `Default` trait. ## Associated consts An associated const is a constant that belongs to a type's namespace instead of the module's: 1. Declare it inside the impl block: `const MIN_TARGET: f64 = 5.0;`. 2. Read it through a path. Inside the impl write `Self::MIN_TARGET`; outside write `Thermostat::MIN_TARGET`. Being in the same impl block does not bring the name into scope: a bare `MAX_TARGET` inside a method is **E0425**, "cannot find value `MAX_TARGET` in this scope", and rustc suggests `Self::MAX_TARGET`. 3. Use it anywhere a constant fits, including a const context such as an array length: `history: [f64; Thermostat::SLOTS]`. Two properties are worth knowing: - An associated const behaves like a `const` item: its value is used wherever it is named, rather than read from one fixed address (the `const` versus `static` difference is covered with constants). - The Reference says associated const definitions are **evaluated only when referenced**. A `const CHECK: () = assert!(Self::SLOTS > 0);` that nobody names never runs; once code names it, a failing assertion becomes a compile error (E0080). Consts declared in a trait, which each implementing type fills in, are covered with associated types. ## Associated functions as values Because an associated function is reached by path, it can be passed wherever a function is expected, with no closure: - `[18.0, 19.0].into_iter().map(Thermostat::new)` builds a `Vec<Thermostat>` from readings. - `thermostats.iter().map(Thermostat::reading)` works because `reading` takes `&Thermostat`, exactly what `iter()` yields. - The same path names a method precisely when two items could share a name; how inherent and trait methods with one name are told apart is covered with trait definitions. ## Several impl blocks, one crate A type may have any number of inherent impl blocks, for example one for construction and one for queries, or blocks under different generic bounds. The Reference adds the limit: the implementing type must be defined in the same crate. `impl String { fn shout(&self) .. }` in your crate fails with **E0116** ("cannot define inherent `impl` for a type outside of the crate where the type is defined"), and for a primitive such as `f64` the error is **E0390**. rustc's own help points to the two ways out: a trait, or a newtype wrapper that your crate owns. ## What interviewers check - You can say why `Thermostat::new` uses `::` and `t.reading()` uses `.`. - You know `Self` is an alias that exists inside an impl, a trait or a type's own definition, not in a free function; written in `main`, `Self::new()` fails with E0433, "cannot find `Self` in this scope". - You reach for an associated const, not a module-level `const`, when a value describes the type itself, such as its valid range.

  • Can you call a method with path syntax, and why would you?
    Yes: `Thermostat::reading(&t)` is the same call as `t.reading()`, with the receiver passed explicitly. It is useful when you pass the method as a function value, as in `.map(Thermostat::reading)` over an iterator of `&Thermostat`, or when you want to name exactly which type's function you mean.
  • When is an associated const evaluated, and what follows from that?
    Only when some code references it. A const whose expression would panic compiles quietly while unused, and fails the build with E0080 once named. That makes associated consts usable as compile-time checks, but only for code paths that actually mention them.
  • Why might a type have more than one inherent impl block?
    To group related items, such as constructors apart from queries, or to give some methods only to certain generic instantiations, like an `impl Buffer<u8>` beside `impl<T> Buffer<T>`. All the blocks must sit in the crate that defines the type.

  • new is a Rust keyword that marks the constructor
  • Items declared in the same impl block are in scope by bare name
  • Associated functions can be called with dot syntax on an instance
  • A type can have only one impl block
  • Any crate may add inherent methods to std's String
open as a page

In Rust, how do you choose between `self`, `&self` and `&mut self` for a method, and what does each leave the caller holding?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Pick the weakest receiver the body needs: &self to read, &mut self to change fields in place, self to consume or convert. The caller keeps its value after the first two; self moves it away unless the type is Copy.

open as a page

In Rust, how does a `Celsius(f64)` newtype stop a Fahrenheit reading reaching `set_target`, and what does the wrapper cost you?

level: middleimportance: should knowfreq 55%

basics

~20 s

A tuple struct such as Celsius(f64) is a distinct type, so passing a Fahrenheit value where Celsius is expected fails with E0308, while a type alias compiles silently. The cost is code: no f64 methods or operators until you add them.

open as a page

In Rust, why is `base` still usable after `Thermostat { room: String::from("office"), ..base }` but not after `Thermostat { target: 23.0, ..base }`?

level: middleimportance: should knowfreq 50%

basics

~20 s

Struct update syntax moves or copies every unlisted field from the base. Taking only Copy fields such as f64 leaves base whole; taking a String field moves it out, so base is partially moved and using it whole is E0382.

open as a page

A Rust `Thermostat::summary(&self)` calls `self.sensor.into_report()`, where `into_report` takes `self`, and fails with E0507: why, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A self receiver needs an owned Sensor, but summary only borrows the thermostat, and moving the field out would leave a hole. Fix it with a borrowing report(&self) on Sensor, a consuming into_summary(self) on Thermostat, or a deliberate clone.

open as a page