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

reuse: add example from tutorial #22

Merged
merged 1 commit into from
Jul 14, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions features/traits/reuse.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,27 @@

> **[OPEN]** We probably want to discourage this, at least when used in a way
> that is publicly exposed.

Traits that provide default implmentations for function can provide code reuse
across types. For example, a `print` method can be defined across multiple
types as follows:

``` Rust
trait Printable {
// Default method implementation
fn print(&self) { println!("{:?}", *self) }
}

impl Printable for int {}

impl Printable for String {
fn print(&self) { println!("{}", *self) }
}

impl Printable for bool {}

impl Printable for f32 {}
```

This allows the implementation of `print` to be shared across types, yet
overridden where needed, as seen in the `impl` for `String`.