Add reference to Self in traits chapter (book)

This commit is contained in:
Panashe M. Fundira 2016-08-21 23:09:18 -04:00
parent 1576de0ce6
commit a5a5c1074e
No known key found for this signature in database
GPG Key ID: ABD6E90F51BF74B5

View File

@ -47,6 +47,28 @@ As you can see, the `trait` block looks very similar to the `impl` block,
but we dont 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