@@ -248,7 +248,7 @@ let v = vec!["Hello world"];
248248```
249249
250250Type inference is trickier for trait objects. For example, say we tried to factor
251- the ` components ` array in Listing 17 -9 into a separate variable, like this:
251+ the ` components ` array in Listing 18 -9 into a separate variable, like this:
252252
253253``` rust,ignore,does_not_compile
254254fn main() {
@@ -261,7 +261,7 @@ fn main() {
261261}
262262```
263263
264- <span class =" caption " >Listing 17 -11: Factoring the components array causes a type error</span >
264+ <span class =" caption " >Listing 18 -11: Factoring the components array causes a type error</span >
265265
266266This refactor causes the program to no longer compile! The compiler rejects this program with
267267the following error:
@@ -281,26 +281,26 @@ error[E0308]: mismatched types
281281 | |_____^ expected `SelectBox`, found `Button`
282282```
283283
284- In Listing 17 -09, the compiler understands that the ` components ` vector must have the type
285- ` Vec<Box<dyn Draw>> ` because that's specified in the ` Screen ` struct definition. But in Listing 17 -11,
284+ In Listing 18 -09, the compiler understands that the ` components ` vector must have the type
285+ ` Vec<Box<dyn Draw>> ` because that's specified in the ` Screen ` struct definition. But in Listing 18 -11,
286286the compiler loses that information at the point where ` components ` is defined. To fix the issue, you
287287have to give a hint to the type inference algorithm. That can either be via an explicit cast on
288288any element of the vector, like this:
289289
290290``` rust,ignore
291- let components = vec![
292- Box::new(SelectBox { /* .. */ }) as Box<dyn Draw>,
293- Box::new(Button { /* .. */ }),
294- ];
291+ let components = vec![
292+ Box::new(SelectBox { /* .. */ }) as Box<dyn Draw>,
293+ Box::new(Button { /* .. */ }),
294+ ];
295295```
296296
297297Or it can be via a type annotation on the let-binding, like this:
298298
299299``` rust,ignore
300- let components: Vec<Box<dyn Draw>> = vec![
301- Box::new(SelectBox { /* .. */ }),
302- Box::new(Button { /* .. */ }),
303- ];
300+ let components: Vec<Box<dyn Draw>> = vec![
301+ Box::new(SelectBox { /* .. */ }),
302+ Box::new(Button { /* .. */ }),
303+ ];
304304```
305305
306306In general, it is good to be aware that using trait objects can cause a worse developer experience for
0 commit comments