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