@@ -3,29 +3,32 @@ The compiler could not infer a type and asked for a type annotation.
3
3
Erroneous code example:
4
4
5
5
``` compile_fail,E0282
6
- let x = "hello".chars().rev().collect ();
6
+ let x = Vec::new ();
7
7
```
8
8
9
9
This error indicates that type inference did not result in one unique possible
10
10
type, and extra information is required. In most cases this can be provided
11
11
by adding a type annotation. Sometimes you need to specify a generic type
12
12
parameter manually.
13
13
14
- A common example is the ` collect ` method on ` Iterator ` . It has a generic type
15
- parameter with a ` FromIterator ` bound, which for a ` char ` iterator is
16
- implemented by ` Vec ` and ` String ` among others. Consider the following snippet
17
- that reverses the characters of a string:
14
+ In the example above, type ` Vec ` has a type parameter ` T ` . When calling
15
+ ` Vec::new ` , barring any other later usage of the variable ` x ` that allows the
16
+ compiler to infer what type ` T ` is, the compiler needs to be told what it is.
18
17
19
- In the first code example, the compiler cannot infer what the type of ` x ` should
20
- be: ` Vec<char> ` and ` String ` are both suitable candidates. To specify which type
21
- to use, you can use a type annotation on ` x ` :
18
+ The type can be specified on the variable:
22
19
23
20
```
24
- let x: Vec<char > = "hello".chars().rev().collect ();
21
+ let x: Vec<i32 > = Vec::new ();
25
22
```
26
23
27
- It is not necessary to annotate the full type. Once the ambiguity is resolved,
28
- the compiler can infer the rest:
24
+ The type can also be specified in the path of the expression:
25
+
26
+ ```
27
+ let x = Vec::<i32>::new();
28
+ ```
29
+
30
+ In cases with more complex types, it is not necessary to annotate the full
31
+ type. Once the ambiguity is resolved, the compiler can infer the rest:
29
32
30
33
```
31
34
let x: Vec<_> = "hello".chars().rev().collect();
0 commit comments