]> git.lizzy.rs Git - rust.git/blob - src/doc/style/features/traits/reuse.md
Changed issue number to 36105
[rust.git] / src / doc / style / features / traits / reuse.md
1 % Using traits to share implementations
2
3 > **[FIXME]** Elaborate.
4
5 > **[FIXME]** We probably want to discourage this, at least when used in a way
6 > that is publicly exposed.
7
8 Traits that provide default implementations 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 i32 {}
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`.