Skip to content

Commit 36c3612

Browse files
committed
Auto merge of #23043 - steveklabnik:doc_default_method, r=nikomatsakis
2 parents 91bdf23 + de44baa commit 36c3612

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/doc/trpl/traits.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,3 +435,46 @@ println!("the inverse of {} is {:?}", 2.0f64, inverse(2.0f64));
435435
println!("the inverse of {} is {:?}", 0.0f32, inverse(0.0f32));
436436
println!("the inverse of {} is {:?}", 0.0f64, inverse(0.0f64));
437437
```
438+
439+
## Default methods
440+
441+
There's one last feature of traits we should cover: default methods. It's
442+
easiest just to show an example:
443+
444+
```rust
445+
trait Foo {
446+
fn bar(&self);
447+
448+
fn baz(&self) { println!("We called baz."); }
449+
}
450+
```
451+
452+
Implementors of the `Foo` trait need to implement `bar()`, but they don't
453+
need to implement `baz()`. They'll get this default behavior. They can
454+
override the default if they so choose:
455+
456+
```rust
457+
# trait Foo {
458+
# fn bar(&self);
459+
# fn baz(&self) { println!("We called baz."); }
460+
# }
461+
struct UseDefault;
462+
463+
impl Foo for UseDefault {
464+
fn bar(&self) { println!("We called bar."); }
465+
}
466+
467+
struct OverrideDefault;
468+
469+
impl Foo for OverrideDefault {
470+
fn bar(&self) { println!("We called bar."); }
471+
472+
fn baz(&self) { println!("Override baz!"); }
473+
}
474+
475+
let default = UseDefault;
476+
default.baz(); // prints "We called bar."
477+
478+
let over = OverrideDefault;
479+
over.baz(); // prints "Override baz!"
480+
```

0 commit comments

Comments
 (0)