1 The compiler could not infer a type and asked for a type annotation.
3 Erroneous code example:
6 let x = "hello".chars().rev().collect();
9 This error indicates that type inference did not result in one unique possible
10 type, and extra information is required. In most cases this can be provided
11 by adding a type annotation. Sometimes you need to specify a generic type
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:
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`:
24 let x: Vec<char> = "hello".chars().rev().collect();
27 It is not necessary to annotate the full type. Once the ambiguity is resolved,
28 the compiler can infer the rest:
31 let x: Vec<_> = "hello".chars().rev().collect();
34 Another way to provide the compiler with enough information, is to specify the
35 generic type parameter:
38 let x = "hello".chars().rev().collect::<Vec<char>>();
41 Again, you need not specify the full type if the compiler can infer it:
44 let x = "hello".chars().rev().collect::<Vec<_>>();
47 Apart from a method or function with a generic type parameter, this error can
48 occur when a type parameter of a struct or trait cannot be inferred. In that
49 case it is not always possible to use a type annotation, because all candidates
50 have the same return type. For instance:
63 let number = Foo::bar();
68 This will fail because the compiler does not know which instance of `Foo` to
69 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.