Skip to content

Commit d5deb11

Browse files
author
Jonathan Turner
authored
Rollup merge of rust-lang#35891 - munyari:book, r=steveklabnik
Add reference to `Self` in traits chapter (book) Addresses rust-lang#31891 "r? @steveklabnik
2 parents 766b04e + 3da5f93 commit d5deb11

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/doc/book/traits.md

+28
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,34 @@ 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+
struct Circle {
56+
x: f64,
57+
y: f64,
58+
radius: f64,
59+
}
60+
61+
trait HasArea {
62+
fn area(&self) -> f64;
63+
64+
fn is_larger(&self, &Self) -> bool;
65+
}
66+
67+
impl HasArea for Circle {
68+
fn area(&self) -> f64 {
69+
std::f64::consts::PI * (self.radius * self.radius)
70+
}
71+
72+
fn is_larger(&self, other: &Self) -> bool {
73+
self.area() > other.area()
74+
}
75+
}
76+
```
77+
5078
## Trait bounds on generic functions
5179

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

0 commit comments

Comments
 (0)