diff options
| author | bors <bors@rust-lang.org> | 2015-03-09 04:35:44 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2015-03-09 04:35:44 +0000 |
| commit | 36c3612f5ceae0fb9df4127bc94a5b443874d1ca (patch) | |
| tree | 983f0ba22502c3577b156e37f42a1f8d27395334 | |
| parent | 91bdf23f504f79ed59617cde3dfebd3d5e39a476 (diff) | |
| parent | de44baac8b0f2eed0fa4c1511e983da431cb2134 (diff) | |
| download | rust-36c3612f5ceae0fb9df4127bc94a5b443874d1ca.tar.gz rust-36c3612f5ceae0fb9df4127bc94a5b443874d1ca.zip | |
Auto merge of #23043 - steveklabnik:doc_default_method, r=nikomatsakis
| -rw-r--r-- | src/doc/trpl/traits.md | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/doc/trpl/traits.md b/src/doc/trpl/traits.md index abd9af1af33..676f1cc425a 100644 --- a/src/doc/trpl/traits.md +++ b/src/doc/trpl/traits.md @@ -435,3 +435,46 @@ println!("the inverse of {} is {:?}", 2.0f64, inverse(2.0f64)); println!("the inverse of {} is {:?}", 0.0f32, inverse(0.0f32)); println!("the inverse of {} is {:?}", 0.0f64, inverse(0.0f64)); ``` + +## Default methods + +There's one last feature of traits we should cover: default methods. It's +easiest just to show an example: + +```rust +trait Foo { + fn bar(&self); + + fn baz(&self) { println!("We called baz."); } +} +``` + +Implementors of the `Foo` trait need to implement `bar()`, but they don't +need to implement `baz()`. They'll get this default behavior. They can +override the default if they so choose: + +```rust +# trait Foo { +# fn bar(&self); +# fn baz(&self) { println!("We called baz."); } +# } +struct UseDefault; + +impl Foo for UseDefault { + fn bar(&self) { println!("We called bar."); } +} + +struct OverrideDefault; + +impl Foo for OverrideDefault { + fn bar(&self) { println!("We called bar."); } + + fn baz(&self) { println!("Override baz!"); } +} + +let default = UseDefault; +default.baz(); // prints "We called bar." + +let over = OverrideDefault; +over.baz(); // prints "Override baz!" +``` |
