Skip to content

Forbid the identifier Self for definitions. #593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 10, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions text/0000-forbid-Self-definitions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
- Start Date: 2015-01-18
- RFC PR: (leave this empty)
- Rust Issue: (leave this empty)

# Summary

Make `Self` a keyword.

# Motivation

Right now, `Self` is just a regular identifier that happens to get a special meaning
inside trait definitions and impls. Specifically, users are not forbidden from defining
a type called `Self`, which can lead to weird situations:

```rust
struct Self;

struct Foo;

impl Foo {
fn foo(&self, _: Self) {}
}
```

This piece of code defines types called `Self` and `Foo`,
and a method `foo()` that because of the special meaning of `Self` has
the signature `fn(&Foo, Foo)`.

So in this case it is not possible to define a method on `Foo` that takes the
actual type `Self` without renaming it or creating a renamed alias.

It would also be highly unidiomatic to actually name the type `Self`
for a custom type, precisely because of this ambiguity, so preventing it outright seems like the right thing to do.

Making the identifier `Self` an keyword would prevent this situation because the user could not use it freely for custom definitions.

# Detailed design

Make the identifier `Self` a keyword that is only legal to use inside a trait definition or impl to refer to the `Self` type.

# Drawbacks

It might be unnecessary churn because people already don't run into this
in practice.

# Alternatives

Keep the status quo. It isn't a problem in practice, and just means
`Self` is the special case of a contextual type definition in the language.

# Unresolved questions

None so far