3 > **<sup>Syntax</sup>**\
5 > [_OuterAttribute_]<sup>\*</sup> (\
6 > [_MacroInvocationSemi_]\
7 > | ( [_Visibility_]<sup>?</sup> ( [_TypeAlias_] | [_ConstantItem_] | [_Function_] ) )\
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 — 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].
16 [associated functions]: #associated-functions-and-methods
17 [associated types]: #associated-types
18 [associated constants]: #associated-constants
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.
24 Every associated item kind comes in two varieties: definitions that contain the
25 actual implementation and declarations that declare signatures for
28 It is the declarations that make up the contract of traits and what is available
31 ## Associated functions and methods
33 *Associated functions* are [functions] associated with a type.
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 `;`.
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.
43 An *associated function definition* defines a function associated with another
44 type. It is written the same as a [function item].
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.
63 let _struct = Struct::new();
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`.
73 fn from_i32(n: i32) -> Self;
77 fn from_i32(n: i32) -> f64 { n as f64 }
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);
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.
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
98 P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P>
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.
108 # use std::sync::Arc;
110 // Examples of methods implemented on struct `Example`.
112 type Alias = Example;
113 trait Trait { type Output; }
114 impl Trait for Example { type Output = 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) {}
130 Shorthand syntax can be used without specifying a type, which have the
131 following equivalents:
133 Shorthand | Equivalent
134 ----------------------|-----------
135 `self` | `self: Self`
136 `&'lifetime self` | `self: &'lifetime Self`
137 `&'lifetime mut self` | `self: &'lifetime mut Self`
139 > **Note**: Lifetimes can be, and usually are, elided with this shorthand.
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:
145 trait Changer: Sized {
146 fn change(mut self) {}
147 fn modify(mut self: Box<Self>) {}
151 As an example of methods on a trait, consider the following:
154 # type Surface = i32;
155 # type BoundingBox = i32;
157 fn draw(&self, surface: Surface);
158 fn bounding_box(&self) -> BoundingBox;
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.
167 # type Surface = i32;
168 # type BoundingBox = i32;
170 # fn draw(&self, surface: Surface);
171 # fn bounding_box(&self) -> BoundingBox;
178 impl Shape for Circle {
180 # fn draw(&self, _: Surface) {}
181 # fn bounding_box(&self) -> BoundingBox { 0i32 }
185 # fn new() -> Circle { Circle{} }
188 let circle_shape = Circle::new();
189 let bounding_box = circle_shape.bounding_box();
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.
196 #### Attributes on method parameters
198 Attributes on method parameters follow the same rules and restrictions as
199 [regular function parameters].
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.
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.
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.
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].
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.
223 Associated types must not include [generic parameters] or [where clauses].
226 trait AssociatedType {
227 // Associated type declaration
235 impl AssociatedType for Struct {
236 // Associated type definition
237 type Assoc = OtherStruct;
241 fn new() -> OtherStruct {
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();
252 ### Associated Types Container Example
254 Consider the following example of a `Container` trait. Notice that the type is
255 available for use in the method signatures:
261 fn insert(&mut self, elem: Self::E);
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`:
272 # fn empty() -> Self;
273 # fn insert(&mut self, elem: Self::E);
275 impl<T> Container for Vec<T> {
277 fn empty() -> Vec<T> { Vec::new() }
278 fn insert(&mut self, x: T) { self.push(x); }
282 ## Associated Constants
284 *Associated constants* are [constants] associated with a type.
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 `;`.
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.
293 An *associated constant definition* defines a constant associated with a
294 type. It is written the same as a [constant item].
296 ### Associated Constants Examples
307 impl ConstantId for Struct {
312 assert_eq!(1, Struct::ID);
316 Using default values:
319 trait ConstantIdDefault {
326 impl ConstantIdDefault for Struct {}
328 impl ConstantIdDefault for OtherStruct {
333 assert_eq!(1, Struct::ID);
334 assert_eq!(5, OtherStruct::ID);
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
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
362 [regular function parameters]: functions.md#attributes-on-function-parameters
363 [generic parameters]: generics.md
364 [where clauses]: generics.md#where-clauses