Skip to content

Commit 8988043

Browse files
committed
Auto merge of #27284 - lastorset:default-methods, r=Gankro
Instead of bar/baz, use valid/invalid as default methods. This illustrates why you might want default methods, and shows that you can call other trait methods from a default method. r? @steveklabnik
2 parents dc6e3bb + 7bec320 commit 8988043

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

src/doc/trpl/traits.md

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -347,40 +347,50 @@ easiest just to show an example:
347347

348348
```rust
349349
trait Foo {
350-
fn bar(&self);
350+
fn is_valid(&self) -> bool;
351351

352-
fn baz(&self) { println!("We called baz."); }
352+
fn is_invalid(&self) -> bool { !self.is_valid() }
353353
}
354354
```
355355

356-
Implementors of the `Foo` trait need to implement `bar()`, but they don’t
357-
need to implement `baz()`. They’ll get this default behavior. They can
356+
Implementors of the `Foo` trait need to implement `is_valid()`, but they don’t
357+
need to implement `is_invalid()`. They’ll get this default behavior. They can
358358
override the default if they so choose:
359359

360360
```rust
361361
# trait Foo {
362-
# fn bar(&self);
363-
# fn baz(&self) { println!("We called baz."); }
362+
# fn is_valid(&self) -> bool;
363+
#
364+
# fn is_invalid(&self) -> bool { !self.is_valid() }
364365
# }
365366
struct UseDefault;
366367

367368
impl Foo for UseDefault {
368-
fn bar(&self) { println!("We called bar."); }
369+
fn is_valid(&self) -> bool {
370+
println!("Called UseDefault.is_valid.");
371+
true
372+
}
369373
}
370374

371375
struct OverrideDefault;
372376

373377
impl Foo for OverrideDefault {
374-
fn bar(&self) { println!("We called bar."); }
378+
fn is_valid(&self) -> bool {
379+
println!("Called OverrideDefault.is_valid.");
380+
true
381+
}
375382

376-
fn baz(&self) { println!("Override baz!"); }
383+
fn is_invalid(&self) -> bool {
384+
println!("Called OverrideDefault.is_invalid!");
385+
true // this implementation is a self-contradiction!
386+
}
377387
}
378388

379389
let default = UseDefault;
380-
default.baz(); // prints "We called baz."
390+
assert!(!default.is_invalid()); // prints "Called UseDefault.is_valid."
381391

382392
let over = OverrideDefault;
383-
over.baz(); // prints "Override baz!"
393+
assert!(over.is_invalid()); // prints "Called OverrideDefault.is_invalid!"
384394
```
385395

386396
# Inheritance

0 commit comments

Comments
 (0)