Skip to content
This repository was archived by the owner on Oct 9, 2018. It is now read-only.

Commit dc764ed

Browse files
committed
Merge pull request #22 from nathantypanski/reuse
reuse: add example from tutorial
2 parents 44930c7 + 3821c83 commit dc764ed

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

features/traits/reuse.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,27 @@
44
55
> **[OPEN]** We probably want to discourage this, at least when used in a way
66
> that is publicly exposed.
7+
8+
Traits that provide default implmentations for function can provide code reuse
9+
across types. For example, a `print` method can be defined across multiple
10+
types as follows:
11+
12+
``` Rust
13+
trait Printable {
14+
// Default method implementation
15+
fn print(&self) { println!("{:?}", *self) }
16+
}
17+
18+
impl Printable for int {}
19+
20+
impl Printable for String {
21+
fn print(&self) { println!("{}", *self) }
22+
}
23+
24+
impl Printable for bool {}
25+
26+
impl Printable for f32 {}
27+
```
28+
29+
This allows the implementation of `print` to be shared across types, yet
30+
overridden where needed, as seen in the `impl` for `String`.

0 commit comments

Comments
 (0)