Skip to content

Commit

Permalink
Rollup merge of rust-lang#35891 - munyari:book, r=steveklabnik
Browse files Browse the repository at this point in the history
Add reference to `Self` in traits chapter (book)

Addresses rust-lang#31891

"r? @steveklabnik
  • Loading branch information
Jonathan Turner committed Aug 22, 2016
2 parents 766b04e + 3da5f93 commit d5deb11
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/doc/book/traits.md
Expand Up @@ -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
Expand Down

0 comments on commit d5deb11

Please sign in to comment.