]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items/associated-items.md
New upstream version 1.55.0+dfsg1
[rustc.git] / src / doc / reference / src / items / associated-items.md
1 # Associated Items
2
3 > **<sup>Syntax</sup>**\
4 > _AssociatedItem_ :\
5 > &nbsp;&nbsp; [_OuterAttribute_]<sup>\*</sup> (\
6 > &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; [_MacroInvocationSemi_]\
7 > &nbsp;&nbsp; &nbsp;&nbsp; | ( [_Visibility_]<sup>?</sup> ( [_TypeAlias_] | [_ConstantItem_] | [_Function_] ) )\
8 > &nbsp;&nbsp; )
9
10 *Associated Items* are the items declared in [traits] or defined in
11 [implementations]. They are called this because they are defined on an associate
12 type &mdash; the type in the implementation. They are a subset of the kinds of
13 items you can declare in a module. Specifically, there are [associated
14 functions] (including methods), [associated types], and [associated constants].
15
16 [associated functions]: #associated-functions-and-methods
17 [associated types]: #associated-types
18 [associated constants]: #associated-constants
19
20 Associated items are useful when the associated item logically is related to the
21 associating item. For example, the `is_some` method on `Option` is intrinsically
22 related to Options, so should be associated.
23
24 Every associated item kind comes in two varieties: definitions that contain the
25 actual implementation and declarations that declare signatures for
26 definitions.
27
28 It is the declarations that make up the contract of traits and what is available
29 on generic types.
30
31 ## Associated functions and methods
32
33 *Associated functions* are [functions] associated with a type.
34
35 An *associated function declaration* declares a signature for an associated
36 function definition. It is written as a function item, except the
37 function body is replaced with a `;`.
38
39 The identifier is the name of the function. The generics, parameter list,
40 return type, and where clause of the associated function must be the same as the
41 associated function declarations's.
42
43 An *associated function definition* defines a function associated with another
44 type. It is written the same as a [function item].
45
46 An example of a common associated function is a `new` function that returns
47 a value of the type the associated function is associated with.
48
49 ```rust
50 struct Struct {
51 field: i32
52 }
53
54 impl Struct {
55 fn new() -> Struct {
56 Struct {
57 field: 0i32
58 }
59 }
60 }
61
62 fn main () {
63 let _struct = Struct::new();
64 }
65 ```
66
67 When the associated function is declared on a trait, the function can also be
68 called with a [path] that is a path to the trait appended by the name of the
69 trait. When this happens, it is substituted for `<_ as Trait>::function_name`.
70
71 ```rust
72 trait Num {
73 fn from_i32(n: i32) -> Self;
74 }
75
76 impl Num for f64 {
77 fn from_i32(n: i32) -> f64 { n as f64 }
78 }
79
80 // These 4 are all equivalent in this case.
81 let _: f64 = Num::from_i32(42);
82 let _: f64 = <_ as Num>::from_i32(42);
83 let _: f64 = <f64 as Num>::from_i32(42);
84 let _: f64 = f64::from_i32(42);
85 ```
86
87 ### Methods
88
89 Associated functions whose first parameter is named `self` are called *methods*
90 and may be invoked using the [method call operator], for example, `x.foo()`, as
91 well as the usual function call notation.
92
93 If the type of the `self` parameter is specified, it is limited to types resolving
94 to one generated by the following grammar (where `'lt` denotes some arbitrary
95 lifetime):
96
97 ```text
98 P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P>
99 S = Self | P
100 ```
101
102 The `Self` terminal in this grammar denotes a type resolving to the implementing type.
103 This can also include the contextual type alias `Self`, other type aliases,
104 or associated type projections resolving to the implementing type.
105
106 ```rust
107 # use std::rc::Rc;
108 # use std::sync::Arc;
109 # use std::pin::Pin;
110 // Examples of methods implemented on struct `Example`.
111 struct Example;
112 type Alias = Example;
113 trait Trait { type Output; }
114 impl Trait for Example { type Output = Example; }
115 impl Example {
116 fn by_value(self: Self) {}
117 fn by_ref(self: &Self) {}
118 fn by_ref_mut(self: &mut Self) {}
119 fn by_box(self: Box<Self>) {}
120 fn by_rc(self: Rc<Self>) {}
121 fn by_arc(self: Arc<Self>) {}
122 fn by_pin(self: Pin<&Self>) {}
123 fn explicit_type(self: Arc<Example>) {}
124 fn with_lifetime<'a>(self: &'a Self) {}
125 fn nested<'a>(self: &mut &'a Arc<Rc<Box<Alias>>>) {}
126 fn via_projection(self: <Example as Trait>::Output) {}
127 }
128 ```
129
130 Shorthand syntax can be used without specifying a type, which have the
131 following equivalents:
132
133 Shorthand | Equivalent
134 ----------------------|-----------
135 `self` | `self: Self`
136 `&'lifetime self` | `self: &'lifetime Self`
137 `&'lifetime mut self` | `self: &'lifetime mut Self`
138
139 > **Note**: Lifetimes can be, and usually are, elided with this shorthand.
140
141 If the `self` parameter is prefixed with `mut`, it becomes a mutable variable,
142 similar to regular parameters using a `mut` [identifier pattern]. For example:
143
144 ```rust
145 trait Changer: Sized {
146 fn change(mut self) {}
147 fn modify(mut self: Box<Self>) {}
148 }
149 ```
150
151 As an example of methods on a trait, consider the following:
152
153 ```rust
154 # type Surface = i32;
155 # type BoundingBox = i32;
156 trait Shape {
157 fn draw(&self, surface: Surface);
158 fn bounding_box(&self) -> BoundingBox;
159 }
160 ```
161
162 This defines a trait with two methods. All values that have [implementations]
163 of this trait while the trait is in scope can have their `draw` and
164 `bounding_box` methods called.
165
166 ```rust
167 # type Surface = i32;
168 # type BoundingBox = i32;
169 # trait Shape {
170 # fn draw(&self, surface: Surface);
171 # fn bounding_box(&self) -> BoundingBox;
172 # }
173 #
174 struct Circle {
175 // ...
176 }
177
178 impl Shape for Circle {
179 // ...
180 # fn draw(&self, _: Surface) {}
181 # fn bounding_box(&self) -> BoundingBox { 0i32 }
182 }
183
184 # impl Circle {
185 # fn new() -> Circle { Circle{} }
186 # }
187 #
188 let circle_shape = Circle::new();
189 let bounding_box = circle_shape.bounding_box();
190 ```
191
192 > **Edition Differences**: In the 2015 edition, it is possible to declare trait
193 > methods with anonymous parameters (e.g. `fn foo(u8)`). This is deprecated and
194 > an error as of the 2018 edition. All parameters must have an argument name.
195
196 #### Attributes on method parameters
197
198 Attributes on method parameters follow the same rules and restrictions as
199 [regular function parameters].
200
201 ## Associated Types
202
203 *Associated types* are [type aliases] associated with another type. Associated
204 types cannot be defined in [inherent implementations] nor can they be given a
205 default implementation in traits.
206
207 An *associated type declaration* declares a signature for associated type
208 definitions. It is written as `type`, then an [identifier], and
209 finally an optional list of trait bounds.
210
211 The identifier is the name of the declared type alias. The optional trait bounds
212 must be fulfilled by the implementations of the type alias.
213 There is an implicit [`Sized`] bound on associated types that can be relaxed using the special `?Sized` bound.
214
215 An *associated type definition* defines a type alias on another type. It is
216 written as `type`, then an [identifier], then an `=`, and finally a [type].
217
218 If a type `Item` has an associated type `Assoc` from a trait `Trait`, then
219 `<Item as Trait>::Assoc` is a type that is an alias of the type specified in the
220 associated type definition. Furthermore, if `Item` is a type parameter, then
221 `Item::Assoc` can be used in type parameters.
222
223 Associated types must not include [generic parameters] or [where clauses].
224
225 ```rust
226 trait AssociatedType {
227 // Associated type declaration
228 type Assoc;
229 }
230
231 struct Struct;
232
233 struct OtherStruct;
234
235 impl AssociatedType for Struct {
236 // Associated type definition
237 type Assoc = OtherStruct;
238 }
239
240 impl OtherStruct {
241 fn new() -> OtherStruct {
242 OtherStruct
243 }
244 }
245
246 fn main() {
247 // Usage of the associated type to refer to OtherStruct as <Struct as AssociatedType>::Assoc
248 let _other_struct: OtherStruct = <Struct as AssociatedType>::Assoc::new();
249 }
250 ```
251
252 ### Associated Types Container Example
253
254 Consider the following example of a `Container` trait. Notice that the type is
255 available for use in the method signatures:
256
257 ```rust
258 trait Container {
259 type E;
260 fn empty() -> Self;
261 fn insert(&mut self, elem: Self::E);
262 }
263 ```
264
265 In order for a type to implement this trait, it must not only provide
266 implementations for every method, but it must specify the type `E`. Here's an
267 implementation of `Container` for the standard library type `Vec`:
268
269 ```rust
270 # trait Container {
271 # type E;
272 # fn empty() -> Self;
273 # fn insert(&mut self, elem: Self::E);
274 # }
275 impl<T> Container for Vec<T> {
276 type E = T;
277 fn empty() -> Vec<T> { Vec::new() }
278 fn insert(&mut self, x: T) { self.push(x); }
279 }
280 ```
281
282 ## Associated Constants
283
284 *Associated constants* are [constants] associated with a type.
285
286 An *associated constant declaration* declares a signature for associated
287 constant definitions. It is written as `const`, then an identifier,
288 then `:`, then a type, finished by a `;`.
289
290 The identifier is the name of the constant used in the path. The type is the
291 type that the definition has to implement.
292
293 An *associated constant definition* defines a constant associated with a
294 type. It is written the same as a [constant item].
295
296 ### Associated Constants Examples
297
298 A basic example:
299
300 ```rust
301 trait ConstantId {
302 const ID: i32;
303 }
304
305 struct Struct;
306
307 impl ConstantId for Struct {
308 const ID: i32 = 1;
309 }
310
311 fn main() {
312 assert_eq!(1, Struct::ID);
313 }
314 ```
315
316 Using default values:
317
318 ```rust
319 trait ConstantIdDefault {
320 const ID: i32 = 1;
321 }
322
323 struct Struct;
324 struct OtherStruct;
325
326 impl ConstantIdDefault for Struct {}
327
328 impl ConstantIdDefault for OtherStruct {
329 const ID: i32 = 5;
330 }
331
332 fn main() {
333 assert_eq!(1, Struct::ID);
334 assert_eq!(5, OtherStruct::ID);
335 }
336 ```
337
338 [_ConstantItem_]: constant-items.md
339 [_Function_]: functions.md
340 [_MacroInvocationSemi_]: ../macros.md#macro-invocation
341 [_OuterAttribute_]: ../attributes.md
342 [_TypeAlias_]: type-aliases.md
343 [_Visibility_]: ../visibility-and-privacy.md
344 [`Arc<Self>`]: ../special-types-and-traits.md#arct
345 [`Box<Self>`]: ../special-types-and-traits.md#boxt
346 [`Pin<P>`]: ../special-types-and-traits.md#pinp
347 [`Rc<Self>`]: ../special-types-and-traits.md#rct
348 [`Sized`]: ../special-types-and-traits.md#sized
349 [traits]: traits.md
350 [type aliases]: type-aliases.md
351 [inherent implementations]: implementations.md#inherent-implementations
352 [identifier]: ../identifiers.md
353 [identifier pattern]: ../patterns.md#identifier-patterns
354 [implementations]: implementations.md
355 [type]: ../types.md#type-expressions
356 [constants]: constant-items.md
357 [constant item]: constant-items.md
358 [functions]: functions.md
359 [function item]: ../types/function-item.md
360 [method call operator]: ../expressions/method-call-expr.md
361 [path]: ../paths.md
362 [regular function parameters]: functions.md#attributes-on-function-parameters
363 [generic parameters]: generics.md
364 [where clauses]: generics.md#where-clauses