Rollup merge of #35891 - munyari:book, r=steveklabnik
Add reference to `Self` in traits chapter (book) Addresses #31891 "r? @steveklabnik
This commit is contained in:
commit
d5deb118f9
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user