]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0282.md
Rollup merge of #93556 - dtolnay:trailingcomma, r=cjgillot
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0282.md
1 The compiler could not infer a type and asked for a type annotation.
2
3 Erroneous code example:
4
5 ```compile_fail,E0282
6 let x = "hello".chars().rev().collect();
7 ```
8
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
12 parameter manually.
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:
18
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`:
22
23 ```
24 let x: Vec<char> = "hello".chars().rev().collect();
25 ```
26
27 It is not necessary to annotate the full type. Once the ambiguity is resolved,
28 the compiler can infer the rest:
29
30 ```
31 let x: Vec<_> = "hello".chars().rev().collect();
32 ```
33
34 Another way to provide the compiler with enough information, is to specify the
35 generic type parameter:
36
37 ```
38 let x = "hello".chars().rev().collect::<Vec<char>>();
39 ```
40
41 Again, you need not specify the full type if the compiler can infer it:
42
43 ```
44 let x = "hello".chars().rev().collect::<Vec<_>>();
45 ```
46
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:
51
52 ```compile_fail,E0282
53 struct Foo<T> {
54     num: T,
55 }
56
57 impl<T> Foo<T> {
58     fn bar() -> i32 {
59         0
60     }
61
62     fn baz() {
63         let number = Foo::bar();
64     }
65 }
66 ```
67
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.