Skip to content

Commit cff264e

Browse files
committed
---
yaml --- r: 193590 b: refs/heads/beta c: ea8434f h: refs/heads/master v: v3
1 parent 26b9819 commit cff264e

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ refs/heads/automation-fail: 1bf06495443584539b958873e04cc2f864ab10e4
3131
refs/heads/issue-18208-method-dispatch-3-quick-reject: 2009f85b9f99dedcec4404418eda9ddba90258a2
3232
refs/heads/batch: b7fd822592a4fb577552d93010c4a4e14f314346
3333
refs/heads/building: 126db549b038c84269a1e4fe46f051b2c15d6970
34-
refs/heads/beta: 1149b4d08d2d52d9225f81b3f7e5225f467d3516
34+
refs/heads/beta: ea8434f7eef703c34051ffad3b8842573a2dc63b
3535
refs/heads/windistfix: 7608dbad651f02e837ed05eef3d74a6662a6e928
3636
refs/tags/1.0.0-alpha: e42bd6d93a1d3433c486200587f8f9e12590a4d7
3737
refs/heads/tmp: de8a23bbc3a7b9cbd7574b5b91a34af59bf030e6

branches/beta/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)