@@ -47,8 +47,11 @@ As you can see, the `trait` block looks very similar to the `impl` block,
47
47
but we don’t define a body, just a type signature. When we ` impl ` a trait,
48
48
we use ` impl Trait for Item ` , rather than just ` impl Item ` .
49
49
50
- We can use traits to constrain our generics. Consider this function, which
51
- does not compile:
50
+ ## Traits bounds for generic functions
51
+
52
+ Traits are useful because they allow a type to make certain promises about its
53
+ behavior. Generic functions can exploit this to constrain the types they
54
+ accept. Consider this function, which does not compile:
52
55
53
56
``` rust,ignore
54
57
fn print_area<T>(shape: T) {
@@ -75,7 +78,7 @@ fn print_area<T: HasArea>(shape: T) {
75
78
}
76
79
```
77
80
78
- The syntax ` <T: HasArea> ` means ` any type that implements the HasArea trait ` .
81
+ The syntax ` <T: HasArea> ` means “ any type that implements the ` HasArea ` trait.”
79
82
Because traits define function type signatures, we can be sure that any type
80
83
which implements ` HasArea ` will have an ` .area() ` method.
81
84
@@ -154,8 +157,8 @@ error: the trait `HasArea` is not implemented for the type `_` [E0277]
154
157
155
158
## Traits bounds for generic structs
156
159
157
- Trait constraints also can apply to implementations for generic structs. Just
158
- append the constraint when you declare type parameters. Here is a new type
160
+ Your generic structs can also benefit from trait constraints. All you need to
161
+ do is append the constraint when you declare type parameters. Here is a new
159
162
type ` Rectangle<T> ` and its operation ` is_square() ` :
160
163
161
164
``` rust
@@ -232,7 +235,7 @@ impl HasArea for i32 {
232
235
It is considered poor style to implement methods on such primitive types, even
233
236
though it is possible.
234
237
235
- This may seem like the Wild West, but there are two other restrictions around
238
+ This may seem like the Wild West, but there are two restrictions around
236
239
implementing traits that prevent this from getting out of hand. The first is
237
240
that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an
238
241
example: the standard library provides a [ ` Write ` ] [ write ] trait which adds
@@ -397,10 +400,10 @@ This shows off the additional feature of `where` clauses: they allow bounds
397
400
where the left-hand side is an arbitrary type (` i32 ` in this case), not just a
398
401
plain type parameter (like ` T ` ).
399
402
400
- ## Default methods
403
+ # Default methods
401
404
402
- There’s one last feature of traits we should cover: default methods. It’s
403
- easiest just to show an example :
405
+ If you already know how a typical implementor will define a method, you can
406
+ let your trait supply a default :
404
407
405
408
``` rust
406
409
trait Foo {
0 commit comments