]> git.lizzy.rs Git - rust.git/blob - src/librustc_error_codes/error_codes/E0307.md
Rollup merge of #67875 - dtolnay:hidden, r=GuillaumeGomez
[rust.git] / src / librustc_error_codes / error_codes / E0307.md
1 This error indicates that the `self` parameter in a method has an invalid
2 "receiver type".
3
4 Methods take a special first parameter, of which there are three variants:
5 `self`, `&self`, and `&mut self`. These are syntactic sugar for
6 `self: Self`, `self: &Self`, and `self: &mut Self` respectively.
7
8 ```
9 # struct Foo;
10 trait Trait {
11     fn foo(&self);
12 //         ^^^^^ `self` here is a reference to the receiver object
13 }
14
15 impl Trait for Foo {
16     fn foo(&self) {}
17 //         ^^^^^ the receiver type is `&Foo`
18 }
19 ```
20
21 The type `Self` acts as an alias to the type of the current trait
22 implementer, or "receiver type". Besides the already mentioned `Self`,
23 `&Self` and `&mut Self` valid receiver types, the following are also valid:
24 `self: Box<Self>`, `self: Rc<Self>`, `self: Arc<Self>`, and `self: Pin<P>`
25 (where P is one of the previous types except `Self`). Note that `Self` can
26 also be the underlying implementing type, like `Foo` in the following
27 example:
28
29 ```
30 # struct Foo;
31 # trait Trait {
32 #     fn foo(&self);
33 # }
34 impl Trait for Foo {
35     fn foo(self: &Foo) {}
36 }
37 ```
38
39 E0307 will be emitted by the compiler when using an invalid reciver type,
40 like in the following example:
41
42 ```compile_fail,E0307
43 # struct Foo;
44 # struct Bar;
45 # trait Trait {
46 #     fn foo(&self);
47 # }
48 impl Trait for Foo {
49     fn foo(self: &Bar) {}
50 }
51 ```
52
53 The nightly feature [Arbintrary self types][AST] extends the accepted
54 set of receiver types to also include any type that can dereference to
55 `Self`:
56
57 ```
58 #![feature(arbitrary_self_types)]
59
60 struct Foo;
61 struct Bar;
62
63 // Because you can dereference `Bar` into `Foo`...
64 impl std::ops::Deref for Bar {
65     type Target = Foo;
66
67     fn deref(&self) -> &Foo {
68         &Foo
69     }
70 }
71
72 impl Foo {
73     fn foo(self: Bar) {}
74 //         ^^^^^^^^^ ...it can be used as the receiver type
75 }
76 ```
77
78 [AST]: https://doc.rust-lang.org/unstable-book/language-features/arbitrary-self-types.html