Skip to content

Commit

Permalink
Add reference to Self in traits chapter (book)
Browse files Browse the repository at this point in the history
  • Loading branch information
munyari committed Aug 22, 2016
1 parent 1576de0 commit a5a5c10
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/doc/book/traits.md
Expand Up @@ -47,6 +47,28 @@ 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
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
Expand Down

0 comments on commit a5a5c10

Please sign in to comment.