Skip to content

Commit 5cf07f1

Browse files
committed
Update patch with example.
1 parent 1b39c0a commit 5cf07f1

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/doc/book/traits.md

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,21 @@ to know more about [operator traits][operators-and-overloading].
243243
# Rules for implementing traits
244244

245245
So far, we’ve only added trait implementations to structs, but you can
246-
implement a trait for any type such as `i32`.
246+
implement a trait for any type such as `f32`:
247+
248+
```rust
249+
trait ApproxEqual {
250+
fn approx_equal(&self, other: &Self) -> bool;
251+
}
252+
impl ApproxEqual for f32 {
253+
fn approx_equal(&self, other: &Self) -> bool {
254+
// Appropriate for `self` and `other` being close to 1.0.
255+
(self - other).abs() <= ::std::f32::EPSILON
256+
}
257+
}
258+
259+
println!("{}", 1.0.approx_equal(&1.00000001));
260+
```
247261

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

0 commit comments

Comments
 (0)