Skip to content

Commit

Permalink
Update patch with example.
Browse files Browse the repository at this point in the history
  • Loading branch information
nwin committed Nov 11, 2016
1 parent 1b39c0a commit 5cf07f1
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/doc/book/traits.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,21 @@ to know more about [operator traits][operators-and-overloading].
# Rules for implementing traits

So far, we’ve only added trait implementations to structs, but you can
implement a trait for any type such as `i32`.
implement a trait for any type such as `f32`:

```rust
trait ApproxEqual {
fn approx_equal(&self, other: &Self) -> bool;
}
impl ApproxEqual for f32 {
fn approx_equal(&self, other: &Self) -> bool {
// Appropriate for `self` and `other` being close to 1.0.
(self - other).abs() <= ::std::f32::EPSILON
}
}

println!("{}", 1.0.approx_equal(&1.00000001));
```

This may seem like the Wild West, but there are two restrictions around
implementing traits that prevent this from getting out of hand. The first is
Expand Down

0 comments on commit 5cf07f1

Please sign in to comment.