Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ae0c1fd

Browse files
authoredNov 11, 2016
Rollup merge of rust-lang#37503 - nwin:patch-3, r=steveklabnik
Remove remark about poor code style The current wording [seems to be confusing](https://www.reddit.com/r/rust/comments/5aat03/why_is_implementing_traits_on_primitive_types/). As an explanation when and why this could be considered as poor style would go beyond of the scope of this chapter I suggest to remove this remark.
2 parents ff9dad0 + 5cf07f1 commit ae0c1fd

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed
 

‎src/doc/book/traits.md

+8-14
Original file line numberDiff line numberDiff line change
@@ -243,28 +243,22 @@ 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. So technically, we _could_ implement `HasArea`
247-
for `i32`:
246+
implement a trait for any type such as `f32`:
248247

249248
```rust
250-
trait HasArea {
251-
fn area(&self) -> f64;
249+
trait ApproxEqual {
250+
fn approx_equal(&self, other: &Self) -> bool;
252251
}
253-
254-
impl HasArea for i32 {
255-
fn area(&self) -> f64 {
256-
println!("this is silly");
257-
258-
*self as f64
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
259256
}
260257
}
261258

262-
5.area();
259+
println!("{}", 1.0.approx_equal(&1.00000001));
263260
```
264261

265-
It is considered poor style to implement methods on such primitive types, even
266-
though it is possible.
267-
268262
This may seem like the Wild West, but there are two restrictions around
269263
implementing traits that prevent this from getting out of hand. The first is
270264
that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an

0 commit comments

Comments
 (0)
Please sign in to comment.