From a5a5c1074e67a5c12157eb88b7a4f055c8938108 Mon Sep 17 00:00:00 2001 From: "Panashe M. Fundira" Date: Sun, 21 Aug 2016 23:09:18 -0400 Subject: [PATCH 1/2] Add reference to `Self` in traits chapter (book) --- src/doc/book/traits.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index e685cb129b939..164a851edeff4 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -47,6 +47,28 @@ As you can see, the `trait` block looks very similar to the `impl` block, but we don’t define a body, only a type signature. When we `impl` a trait, we use `impl Trait for Item`, rather than only `impl Item`. +`Self` may be used in a type annotation to refer to an instance of the type +implementing this trait passed as a parameter. `Self`, `&Self` or `&mut Self` +may be used depending on the level of ownership required. + +```rust +trait HasArea { + fn area(&self) -> f64; + + fn is_larger(&self, &Self) -> bool; +} + +impl HasArea for Circle { + fn area(&self) -> f64 { + std::f64::consts::PI * (self.radius * self.radius) + } + + fn is_larger(&self, other: &Self) -> bool { + self.area() > other.area() + } +} +``` + ## Trait bounds on generic functions Traits are useful because they allow a type to make certain promises about its From 3da5f9327a3a54a280a299fd38ff8376d3d5d419 Mon Sep 17 00:00:00 2001 From: "Panashe M. Fundira" Date: Mon, 22 Aug 2016 12:10:02 -0400 Subject: [PATCH 2/2] Correct failing book test --- src/doc/book/traits.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index 164a851edeff4..9cbb514e28065 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -52,6 +52,12 @@ implementing this trait passed as a parameter. `Self`, `&Self` or `&mut Self` may be used depending on the level of ownership required. ```rust +struct Circle { + x: f64, + y: f64, + radius: f64, +} + trait HasArea { fn area(&self) -> f64;