Why associated functions require a parameter named `self`?

Does anyone know what's the rationale for requiring the "self" parameter to be named self? I understand why we need a parameter for self, I just don't understand why it's required to be named "self".

For example, this code compiles fine:

struct Foo {}

impl Foo {
    fn foo(self: Self) {}
}

fn main() {
    Foo {}.foo();
}

But this one doesn't:

struct Foo {}

impl Foo {
    fn foo(some_other_name: Self) {}
}

fn main() {
    Foo {}.foo();
}

The error we get is:

error[E0599]: no method named `foo` found for struct `Foo` in the current scope
 --> src/main.rs:8:12
  |
1 | struct Foo {}
  | ---------- method `foo` not found for this struct
...
8 |     Foo {}.foo();
  |     -------^^^--
  |     |      |
  |     |      this is an associated function, not a method
  |     help: use associated function syntax instead: `Foo::foo(Foo {})`
  |
  = note: found the following associated functions; to be used as methods, functions must have a `self` parameter

Rust forbids it just because it's not named self. But in practice it could work just fine. I mean, "self" could be a convention but wouldn't need to be a requirement.

Parameter name self is not required, but has a special meaning. It allows method call syntax.
Notice, that you got no error at a function definition site. You can call it like this:
Foo::foo(Foo{})

Right, thanks. I understand that. I'd just like to know if someone knows why it has a special meaning. Everything could work just as fine if it didn't have that special meaning.

This is so one can choose to have a function with an argument of Self, which is not callable as method - only as a function on the type. Check, for example, Box::into_raw and similar functions: they should not be callable as box.into_raw(), or otherwise the same-named method on the underlying value would be shadowed by the method on a Box itself.

2 Likes

Thank you! That makes total sense.