Warning
This post was published 38 days ago. The information described in this article may have changed.
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.
5 posts - 3 participants
🏷️ rust_feed