@@ -3,29 +3,32 @@ The compiler could not infer a type and asked for a type annotation.
33Erroneous code example:
44
55``` compile_fail,E0282
6- let x = "hello".chars().rev().collect ();
6+ let x = Vec::new ();
77```
88
99This error indicates that type inference did not result in one unique possible
1010type, and extra information is required. In most cases this can be provided
1111by adding a type annotation. Sometimes you need to specify a generic type
1212parameter manually.
1313
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.
1817
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:
2219
2320```
24- let x: Vec<char > = "hello".chars().rev().collect ();
21+ let x: Vec<i32 > = Vec::new ();
2522```
2623
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:
2932
3033```
3134let x: Vec<_> = "hello".chars().rev().collect();
0 commit comments