From 1b39c0a602ad316b8eebd2dd50ae14e45d47dd13 Mon Sep 17 00:00:00 2001 From: nwin Date: Mon, 31 Oct 2016 19:43:50 +0100 Subject: [PATCH 1/2] 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. --- src/doc/book/traits.md | 22 +--------------------- 1 file changed, 1 insertion(+), 21 deletions(-) diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index b0d954adf67..18e7f07f722 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -243,27 +243,7 @@ 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`: - -```rust -trait HasArea { - fn area(&self) -> f64; -} - -impl HasArea for i32 { - fn area(&self) -> f64 { - println!("this is silly"); - - *self as f64 - } -} - -5.area(); -``` - -It is considered poor style to implement methods on such primitive types, even -though it is possible. +implement a trait for any type such as `i32`. 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 From 5cf07f1d60f38491339b3c3b963aca3622674891 Mon Sep 17 00:00:00 2001 From: nwin Date: Fri, 4 Nov 2016 10:50:58 +0100 Subject: [PATCH 2/2] Update patch with example. --- src/doc/book/traits.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index 18e7f07f722..d1166e686c7 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -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