@@ -206,10 +206,19 @@ fn bar() {
206
206
207
207
### ` Self `
208
208
209
- ` Self ` , with a capital "S", is used to refer to the implementing type within
210
- [ traits] and [ implementations] .
209
+ ` Self ` , with a capital "S", is used to refer to the current type being implemented or defined. It may be used in the following situations:
210
+
211
+ * In a [ trait] definition, it refers to the type implementing the trait.
212
+ * In an [ implementation] , it refers to the implementing type.
213
+ When implementing a tuple or unit [ struct] , [ enumeration] , or [ union] , it also refers to the constructor in the [ value namespace] .
214
+ * In the definition of a [ struct] , [ enumeration] , or [ union] , it refers to the defining type.
215
+ The definition is not allowed to be infinitely recursive (there must be an indirection).
216
+
217
+ The scope of ` Self ` behaves similarly to a generic parameter, see the [ scopes chapter] for more details.
218
+ <!-- TODO: update link to #self-scope once https://github.com/rust-lang/reference/pull/1040 is merged. -->
211
219
212
220
` Self ` can only be used as the first segment, without a preceding ` :: ` .
221
+ The ` Self ` path cannot include generic arguments (as in ` Self::<i32> ` ).
213
222
214
223
``` rust
215
224
trait T {
@@ -231,6 +240,20 @@ impl T for S {
231
240
Self :: C // `Self::C` is the constant value `9`.
232
241
}
233
242
}
243
+
244
+ // `Self` is in scope within the generics of a trait definition,
245
+ // to refer to the defining type.
246
+ trait Add <Rhs = Self > {
247
+ type Output ;
248
+ // `Self` can also reference associated items of the implementing types.
249
+ fn add (self , rhs : Rhs ) -> Self :: Output ;
250
+ }
251
+
252
+ struct NonEmptyList <T > {
253
+ head : T ,
254
+ // A struct can reference itself (as long as it is not infinitely recursive).
255
+ tail : Option <Box <NonEmptyList <T >>>,
256
+ }
234
257
```
235
258
236
259
### ` super `
@@ -387,13 +410,20 @@ mod without { // ::without
387
410
[ IDENTIFIER ] : identifiers.md
388
411
[ `use` ] : items/use-declarations.md
389
412
[ attributes ] : attributes.md
413
+ [ enumeration ] : items/enumerations.md
390
414
[ expressions ] : expressions.md
391
415
[ extern prelude ] : names/preludes.md#extern-prelude
416
+ [ implementation ] : items/implementations.md
392
417
[ macro transcribers ] : macros-by-example.md
393
418
[ macros ] : macros.md
394
419
[ mbe ] : macros-by-example.md
395
420
[ patterns ] : patterns.md
421
+ [ scopes chapter ] : names/scopes.md
422
+ [ struct ] : items/structs.md
396
423
[ trait implementations ] : items/implementations.md#trait-implementations
424
+ [ trait ] : items/traits.md
397
425
[ traits ] : items/traits.md
398
426
[ types ] : types.md
427
+ [ union ] : items/unions.md
428
+ [ value namespace ] : names/namespaces.md
399
429
[ visibility ] : visibility-and-privacy.md
0 commit comments