@@ -54,15 +54,16 @@ trait Trait {}
54
54
55
55
impl Trait for i32 {}
56
56
57
- fn returns_a_trait_object () -> Box <Trait > {
57
+ fn returns_a_trait_object () -> Box <dyn Trait > {
58
58
Box :: new (5 )
59
59
}
60
60
```
61
61
62
62
However, this has some overhead: the ` Box<T> ` means that there's a heap
63
- allocation here, and this will use dynamic dispatch. But we only ever
64
- return one possible thing here, the ` Box<i32> ` . This means that we're
65
- paying for dynamic dispatch, even though we don't use it!
63
+ allocation here, and this will use dynamic dispatch. See the [ ` dyn Trait ` ] section
64
+ for an explanation of this syntax. But we only ever return one possible thing
65
+ here, the ` Box<i32> ` . This means that we're paying for dynamic dispatch, even
66
+ though we don't use it!
66
67
67
68
With ` impl Trait ` , the code above could be written like this:
68
69
@@ -82,6 +83,8 @@ we still can obscure the `i32` return type.
82
83
With ` i32 ` , this isn't super useful. But there's one major place in Rust
83
84
where this is much more useful: closures.
84
85
86
+ [ `dyn Trait` ] : /2018/transitioning/traits/dyn-trait.html
87
+
85
88
### ` impl Trait ` and closures
86
89
87
90
> If you need to catch up on closures, check out [ their chapter in the
@@ -92,7 +95,7 @@ family of traits, however. This means that previously, the only way to return
92
95
a closure from a function was to use a trait object:
93
96
94
97
``` rust
95
- fn returns_closure () -> Box <Fn (i32 ) -> i32 > {
98
+ fn returns_closure () -> Box <dyn Fn (i32 ) -> i32 > {
96
99
Box :: new (| x | x + 1 )
97
100
}
98
101
```
0 commit comments