diff options
| author | Nick Hamann <nick@wabbo.org> | 2015-05-12 23:33:10 -0500 |
|---|---|---|
| committer | Nick Hamann <nick@wabbo.org> | 2015-05-12 23:33:10 -0500 |
| commit | 857a12a01ed8a9249cea8f48b39a0f8bdfd95cbd (patch) | |
| tree | 8ab0f4c58806764207cfe75c46e36ca5587e9445 /src/doc/reference.md | |
| parent | c2b30b86df6b34ba19e87e63402e43d9e81a64fb (diff) | |
| download | rust-857a12a01ed8a9249cea8f48b39a0f8bdfd95cbd.tar.gz rust-857a12a01ed8a9249cea8f48b39a0f8bdfd95cbd.zip | |
Expand the "Traits" section of the reference.
Diffstat (limited to 'src/doc/reference.md')
| -rw-r--r-- | src/doc/reference.md | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/doc/reference.md b/src/doc/reference.md index 2ddec9ba424..03b55309836 100644 --- a/src/doc/reference.md +++ b/src/doc/reference.md @@ -1346,6 +1346,8 @@ vtable when the trait is used as a [trait object](#trait-objects). Traits are implemented for specific types through separate [implementations](#implementations). +Consider the following trait: + ``` # type Surface = i32; # type BoundingBox = i32; @@ -1360,6 +1362,20 @@ This defines a trait with two methods. All values that have `draw` and `bounding_box` methods called, using `value.bounding_box()` [syntax](#method-call-expressions). +Traits can include default implementations of methods, as in: + +``` +trait Foo { + fn bar(&self); + + fn baz(&self) { println!("We called baz."); } +} +``` + +Here the `baz` method has a default implementation, so types that implement +`Foo` need only implement `bar`. It is also possible for implementing types +to override a method that has a default implementation. + Type parameters can be specified for a trait to make it generic. These appear after the trait name, using the same syntax used in [generic functions](#generic-functions). @@ -1372,6 +1388,30 @@ trait Seq<T> { } ``` +It is also possible to define associated types for a trait. Consider the +following example of a `Container` trait. Notice how the type is available +for use in the method signatures: + +``` +trait Container { + type E; + fn empty() -> Self; + fn insert(&mut self, Self::E); +} +``` + +In order for a type to implement this trait, it must not only provide +implementations for every method, but it must specify the type `E`. Here's +an implementation of `Container` for the standard library type `Vec`: + +``` +impl<T> Container for Vec<T> { + type E = T; + fn empty() -> Vec<T> { Vec::new() } + fn insert(&mut self, x: T) { self.push(x); } +} +``` + Generic functions may use traits as _bounds_ on their type parameters. This will have two effects: only types that have the trait may instantiate the parameter, and within the generic function, the methods of the trait can be |
