diff options
| author | Jonathan Turner <jonathandturner@users.noreply.github.com> | 2016-08-22 15:34:22 -0700 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2016-08-22 15:34:22 -0700 |
| commit | d5deb118f999e5603944deded5e1f87b167325ff (patch) | |
| tree | ebba8f5369e1c77963d5a304741a27b8de29eb00 | |
| parent | 766b04ec5e4657381f5920a79d10d2d19cb87c61 (diff) | |
| parent | 3da5f9327a3a54a280a299fd38ff8376d3d5d419 (diff) | |
| download | rust-d5deb118f999e5603944deded5e1f87b167325ff.tar.gz rust-d5deb118f999e5603944deded5e1f87b167325ff.zip | |
Rollup merge of #35891 - munyari:book, r=steveklabnik
Add reference to `Self` in traits chapter (book) Addresses #31891 "r? @steveklabnik
| -rw-r--r-- | src/doc/book/traits.md | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/src/doc/book/traits.md b/src/doc/book/traits.md index e685cb129b9..9cbb514e280 100644 --- a/src/doc/book/traits.md +++ b/src/doc/book/traits.md @@ -47,6 +47,34 @@ 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 +struct Circle { + x: f64, + y: f64, + radius: f64, +} + +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 |
