]> git.lizzy.rs Git - rust.git/blob - src/librustc_error_codes/error_codes/E0282.md
Rollup merge of #67943 - Stromberg90:patch-1, r=jonas-schievink
[rust.git] / src / librustc_error_codes / error_codes / E0282.md
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
4 parameter manually.
5
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:
10
11 ```compile_fail,E0282
12 let x = "hello".chars().rev().collect();
13 ```
14
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`:
18
19 ```
20 let x: Vec<char> = "hello".chars().rev().collect();
21 ```
22
23 It is not necessary to annotate the full type. Once the ambiguity is resolved,
24 the compiler can infer the rest:
25
26 ```
27 let x: Vec<_> = "hello".chars().rev().collect();
28 ```
29
30 Another way to provide the compiler with enough information, is to specify the
31 generic type parameter:
32
33 ```
34 let x = "hello".chars().rev().collect::<Vec<char>>();
35 ```
36
37 Again, you need not specify the full type if the compiler can infer it:
38
39 ```
40 let x = "hello".chars().rev().collect::<Vec<_>>();
41 ```
42
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:
47
48 ```compile_fail,E0282
49 struct Foo<T> {
50     num: T,
51 }
52
53 impl<T> Foo<T> {
54     fn bar() -> i32 {
55         0
56     }
57
58     fn baz() {
59         let number = Foo::bar();
60     }
61 }
62 ```
63
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.