about summary refs log tree commit diff
diff options
context:
space:
mode:
authorLeif Arne Storset <leifarne@storset.net>2015-07-25 18:18:47 +0200
committerLeif Arne Storset <leifarne@storset.net>2015-07-25 20:53:57 +0200
commit7bec320e6e067b9886f66f8c5d75e4bfef633f52 (patch)
tree85322e33c42e11143bfa089cb83f59e96dcf2899
parent04badd6a973d2499731b49365a121dbc4c9c468e (diff)
downloadrust-7bec320e6e067b9886f66f8c5d75e4bfef633f52.tar.gz
rust-7bec320e6e067b9886f66f8c5d75e4bfef633f52.zip
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.
-rw-r--r--src/doc/trpl/traits.md32
1 files changed, 21 insertions, 11 deletions
diff --git a/src/doc/trpl/traits.md b/src/doc/trpl/traits.md
index 687e2bbf00e..740e2d51c4c 100644
--- a/src/doc/trpl/traits.md
+++ b/src/doc/trpl/traits.md
@@ -347,40 +347,50 @@ easiest just to show an example:
 
 ```rust
 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 don’t
-need to implement `baz()`. They’ll get this default behavior. They can
+Implementors of the `Foo` trait need to implement `is_valid()`, but they don’t
+need to implement `is_invalid()`. 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."); }
+#     fn is_valid(&self) -> bool;
+#
+#     fn is_invalid(&self) -> bool { !self.is_valid() }
 # }
 struct 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;
 
 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;
-default.baz(); // prints "We called baz."
+assert!(!default.is_invalid()); // prints "Called UseDefault.is_valid."
 
 let over = OverrideDefault;
-over.baz(); // prints "Override baz!"
+assert!(over.is_invalid()); // prints "Called OverrideDefault.is_invalid!"
 ```
 
 # Inheritance