Skip to content

Commit 857a12a

Browse files
author
Nick Hamann
committed
Expand the "Traits" section of the reference.
1 parent c2b30b8 commit 857a12a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/doc/reference.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1346,6 +1346,8 @@ vtable when the trait is used as a [trait object](#trait-objects).
13461346
Traits are implemented for specific types through separate
13471347
[implementations](#implementations).
13481348

1349+
Consider the following trait:
1350+
13491351
```
13501352
# type Surface = i32;
13511353
# type BoundingBox = i32;
@@ -1360,6 +1362,20 @@ This defines a trait with two methods. All values that have
13601362
`draw` and `bounding_box` methods called, using `value.bounding_box()`
13611363
[syntax](#method-call-expressions).
13621364

1365+
Traits can include default implementations of methods, as in:
1366+
1367+
```
1368+
trait Foo {
1369+
fn bar(&self);
1370+
1371+
fn baz(&self) { println!("We called baz."); }
1372+
}
1373+
```
1374+
1375+
Here the `baz` method has a default implementation, so types that implement
1376+
`Foo` need only implement `bar`. It is also possible for implementing types
1377+
to override a method that has a default implementation.
1378+
13631379
Type parameters can be specified for a trait to make it generic. These appear
13641380
after the trait name, using the same syntax used in [generic
13651381
functions](#generic-functions).
@@ -1372,6 +1388,30 @@ trait Seq<T> {
13721388
}
13731389
```
13741390

1391+
It is also possible to define associated types for a trait. Consider the
1392+
following example of a `Container` trait. Notice how the type is available
1393+
for use in the method signatures:
1394+
1395+
```
1396+
trait Container {
1397+
type E;
1398+
fn empty() -> Self;
1399+
fn insert(&mut self, Self::E);
1400+
}
1401+
```
1402+
1403+
In order for a type to implement this trait, it must not only provide
1404+
implementations for every method, but it must specify the type `E`. Here's
1405+
an implementation of `Container` for the standard library type `Vec`:
1406+
1407+
```
1408+
impl<T> Container for Vec<T> {
1409+
type E = T;
1410+
fn empty() -> Vec<T> { Vec::new() }
1411+
fn insert(&mut self, x: T) { self.push(x); }
1412+
}
1413+
```
1414+
13751415
Generic functions may use traits as _bounds_ on their type parameters. This
13761416
will have two effects: only types that have the trait may instantiate the
13771417
parameter, and within the generic function, the methods of the trait can be

0 commit comments

Comments
 (0)