diff options
| author | Eduard-Mihai Burtescu <edy.burt@gmail.com> | 2016-11-12 10:38:37 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2016-11-12 10:38:37 +0200 |
| commit | 16ae078fe994535f3b362c6af0389549b6516063 (patch) | |
| tree | f80041d64eb855892cc1ac80216b6d9cf11382d6 /src/doc | |
| parent | 7894d2aad68be19a7e97194e3df4ec835ca524b6 (diff) | |
| parent | 5cf07f1d60f38491339b3c3b963aca3622674891 (diff) | |
| download | rust-16ae078fe994535f3b362c6af0389549b6516063.tar.gz rust-16ae078fe994535f3b362c6af0389549b6516063.zip | |
Rollup merge of #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.
Diffstat (limited to 'src/doc')
| -rw-r--r-- | src/doc/book/traits.md | 22 |
1 files changed, 8 insertions, 14 deletions
diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index b0d954adf67..d1166e686c7 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -243,28 +243,22 @@ 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. So technically, we _could_ implement `HasArea` -for `i32`: +implement a trait for any type such as `f32`: ```rust -trait HasArea { - fn area(&self) -> f64; +trait ApproxEqual { + fn approx_equal(&self, other: &Self) -> bool; } - -impl HasArea for i32 { - fn area(&self) -> f64 { - println!("this is silly"); - - *self as f64 +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 } } -5.area(); +println!("{}", 1.0.approx_equal(&1.00000001)); ``` -It is considered poor style to implement methods on such primitive types, even -though it is possible. - 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 that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an |
