Skip to content

Commit a5a5c10

Browse files
committed
Add reference to Self in traits chapter (book)
1 parent 1576de0 commit a5a5c10

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/doc/book/traits.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,28 @@ As you can see, the `trait` block looks very similar to the `impl` block,
4747
but we don’t define a body, only a type signature. When we `impl` a trait,
4848
we use `impl Trait for Item`, rather than only `impl Item`.
4949

50+
`Self` may be used in a type annotation to refer to an instance of the type
51+
implementing this trait passed as a parameter. `Self`, `&Self` or `&mut Self`
52+
may be used depending on the level of ownership required.
53+
54+
```rust
55+
trait HasArea {
56+
fn area(&self) -> f64;
57+
58+
fn is_larger(&self, &Self) -> bool;
59+
}
60+
61+
impl HasArea for Circle {
62+
fn area(&self) -> f64 {
63+
std::f64::consts::PI * (self.radius * self.radius)
64+
}
65+
66+
fn is_larger(&self, other: &Self) -> bool {
67+
self.area() > other.area()
68+
}
69+
}
70+
```
71+
5072
## Trait bounds on generic functions
5173

5274
Traits are useful because they allow a type to make certain promises about its

0 commit comments

Comments
 (0)