@@ -221,10 +221,19 @@ impl S {
221
221
222
222
### ` Self `
223
223
224
- ` Self ` , with a capital "S", is used to refer to the implementing type within
225
- [ traits] and [ implementations] .
224
+ ` 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:
225
+
226
+ * In a [ trait] definition, it refers to the type implementing the trait.
227
+ * In an [ implementation] , it refers to the implementing type.
228
+ When implementing a tuple or unit [ struct] , [ enumeration] , or [ union] , it also refers to the constructor in the [ value namespace] .
229
+ * In the definition of a [ struct] , [ enumeration] , or [ union] , it refers to the defining type.
230
+ The definition is not allowed to be infinitely recursive (there must be an indirection).
231
+
232
+ The scope of ` Self ` behaves similarly to a generic parameter, see the [ scopes chapter] for more details.
233
+ <!-- TODO: update link to #self-scope once https://github.com/rust-lang/reference/pull/1040 is merged. -->
226
234
227
235
` Self ` can only be used as the first segment, without a preceding ` :: ` .
236
+ The ` Self ` path cannot include generic arguments (as in ` Self::<i32> ` ).
228
237
229
238
``` rust
230
239
trait T {
@@ -246,6 +255,20 @@ impl T for S {
246
255
Self :: C // `Self::C` is the constant value `9`.
247
256
}
248
257
}
258
+
259
+ // `Self` is in scope within the generics of a trait definition,
260
+ // to refer to the defining type.
261
+ trait Add <Rhs = Self > {
262
+ type Output ;
263
+ // `Self` can also reference associated items of the implementing types.
264
+ fn add (self , rhs : Rhs ) -> Self :: Output ;
265
+ }
266
+
267
+ struct NonEmptyList <T > {
268
+ head : T ,
269
+ // A struct can reference itself (as long as it is not infinitely recursive).
270
+ tail : Option <Box <NonEmptyList <T >>>,
271
+ }
249
272
```
250
273
251
274
### ` super `
@@ -404,13 +427,20 @@ mod without { // crate::without
404
427
[ IDENTIFIER ] : identifiers.md
405
428
[ `use` ] : items/use-declarations.md
406
429
[ attributes ] : attributes.md
430
+ [ enumeration ] : items/enumerations.md
407
431
[ expressions ] : expressions.md
408
432
[ extern prelude ] : names/preludes.md#extern-prelude
433
+ [ implementation ] : items/implementations.md
409
434
[ macro transcribers ] : macros-by-example.md
410
435
[ macros ] : macros.md
411
436
[ mbe ] : macros-by-example.md
412
437
[ patterns ] : patterns.md
438
+ [ scopes chapter ] : names/scopes.md
439
+ [ struct ] : items/structs.md
413
440
[ trait implementations ] : items/implementations.md#trait-implementations
441
+ [ trait ] : items/traits.md
414
442
[ traits ] : items/traits.md
415
443
[ types ] : types.md
444
+ [ union ] : items/unions.md
445
+ [ value namespace ] : names/namespaces.md
416
446
[ visibility ] : visibility-and-privacy.md
0 commit comments