@@ -375,39 +375,40 @@ by adding a type annotation. Sometimes you need to specify a generic type
375
375
parameter manually.
376
376
377
377
A common example is the `collect` method on `Iterator`. It has a generic type
378
- parameter with a `FromIterator` bound, which is implemented by `Vec` and
379
- `VecDeque` among others. Consider the following snippet:
378
+ parameter with a `FromIterator` bound, which for a `char` iterator is
379
+ implemented by `Vec` and `String` among others. Consider the following snippet
380
+ that reverses the characters of a string:
380
381
381
382
```
382
- let x = (1_i32 .. 10 ).collect();
383
+ let x = "hello".chars().rev( ).collect();
383
384
```
384
385
385
386
In this case, the compiler cannot infer what the type of `x` should be:
386
- `Vec<i32 >` and `VecDeque<i32> ` are both suitable candidates. To specify which
387
- type to use, you can use a type annotation on `x`:
387
+ `Vec<char >` and `String ` are both suitable candidates. To specify which type to
388
+ use, you can use a type annotation on `x`:
388
389
389
390
```
390
- let x: Vec<i32 > = (1_i32 .. 10 ).collect();
391
+ let x: Vec<char > = "hello".chars().rev( ).collect();
391
392
```
392
393
393
- It is not necessary to annotate the full type, once the ambiguity is resolved,
394
+ It is not necessary to annotate the full type. Once the ambiguity is resolved,
394
395
the compiler can infer the rest:
395
396
396
397
```
397
- let x: Vec<_> = (1_i32 .. 10 ).collect();
398
+ let x: Vec<_> = "hello".chars().rev( ).collect();
398
399
```
399
400
400
401
Another way to provide the compiler with enough information, is to specify the
401
402
generic type parameter:
402
403
403
404
```
404
- let x = (1_i32 .. 10 ).collect::<Vec<i32 >>();
405
+ let x = "hello".chars().rev( ).collect::<Vec<char >>();
405
406
```
406
407
407
408
Again, you need not specify the full type if the compiler can infer it:
408
409
409
410
```
410
- let x = (1_i32 .. 10 ).collect::<Vec<_>>();
411
+ let x = "hello".chars().rev( ).collect::<Vec<_>>();
411
412
```
412
413
413
414
Apart from a method or function with a generic type parameter, this error can
0 commit comments