1 This error indicates that type inference did not result in one unique possible
2 type, and extra information is required. In most cases this can be provided
3 by adding a type annotation. Sometimes you need to specify a generic type
6 A common example is the `collect` method on `Iterator`. It has a generic type
7 parameter with a `FromIterator` bound, which for a `char` iterator is
8 implemented by `Vec` and `String` among others. Consider the following snippet
9 that reverses the characters of a string:
12 let x = "hello".chars().rev().collect();
15 In this case, the compiler cannot infer what the type of `x` should be:
16 `Vec<char>` and `String` are both suitable candidates. To specify which type to
17 use, you can use a type annotation on `x`:
20 let x: Vec<char> = "hello".chars().rev().collect();
23 It is not necessary to annotate the full type. Once the ambiguity is resolved,
24 the compiler can infer the rest:
27 let x: Vec<_> = "hello".chars().rev().collect();
30 Another way to provide the compiler with enough information, is to specify the
31 generic type parameter:
34 let x = "hello".chars().rev().collect::<Vec<char>>();
37 Again, you need not specify the full type if the compiler can infer it:
40 let x = "hello".chars().rev().collect::<Vec<_>>();
43 Apart from a method or function with a generic type parameter, this error can
44 occur when a type parameter of a struct or trait cannot be inferred. In that
45 case it is not always possible to use a type annotation, because all candidates
46 have the same return type. For instance:
59 let number = Foo::bar();
64 This will fail because the compiler does not know which instance of `Foo` to
65 call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.