Default methods example: Show "(in)valid" case

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.
This commit is contained in:
Leif Arne Storset 2015-07-25 18:18:47 +02:00
parent 04badd6a97
commit 7bec320e6e

View File

@ -347,40 +347,50 @@ easiest just to show an example:
```rust ```rust
trait Foo { trait Foo {
fn bar(&self); fn is_valid(&self) -> bool;
fn baz(&self) { println!("We called baz."); } fn is_invalid(&self) -> bool { !self.is_valid() }
} }
``` ```
Implementors of the `Foo` trait need to implement `bar()`, but they dont Implementors of the `Foo` trait need to implement `is_valid()`, but they dont
need to implement `baz()`. Theyll get this default behavior. They can need to implement `is_invalid()`. Theyll get this default behavior. They can
override the default if they so choose: override the default if they so choose:
```rust ```rust
# trait Foo { # trait Foo {
# fn bar(&self); # fn is_valid(&self) -> bool;
# fn baz(&self) { println!("We called baz."); } #
# fn is_invalid(&self) -> bool { !self.is_valid() }
# } # }
struct UseDefault; struct UseDefault;
impl Foo for UseDefault { impl Foo for UseDefault {
fn bar(&self) { println!("We called bar."); } fn is_valid(&self) -> bool {
println!("Called UseDefault.is_valid.");
true
}
} }
struct OverrideDefault; struct OverrideDefault;
impl Foo for OverrideDefault { impl Foo for OverrideDefault {
fn bar(&self) { println!("We called bar."); } fn is_valid(&self) -> bool {
println!("Called OverrideDefault.is_valid.");
true
}
fn baz(&self) { println!("Override baz!"); } fn is_invalid(&self) -> bool {
println!("Called OverrideDefault.is_invalid!");
true // this implementation is a self-contradiction!
}
} }
let default = UseDefault; let default = UseDefault;
default.baz(); // prints "We called baz." assert!(!default.is_invalid()); // prints "Called UseDefault.is_valid."
let over = OverrideDefault; let over = OverrideDefault;
over.baz(); // prints "Override baz!" assert!(over.is_invalid()); // prints "Called OverrideDefault.is_invalid!"
``` ```
# Inheritance # Inheritance