blob: b2f0ede6a0b68655f981b33e77b29d0f99acd395 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
The compiler could not infer a type and asked for a type annotation.
Erroneous code example:
```compile_fail,E0283
let x = "hello".chars().rev().collect();
```
This error indicates that type inference did not result in one unique possible
type, and extra information is required. In most cases this can be provided
by adding a type annotation. Sometimes you need to specify a generic type
parameter manually.
A common example is the `collect` method on `Iterator`. It has a generic type
parameter with a `FromIterator` bound, which for a `char` iterator is
implemented by `Vec` and `String` among others. Consider the following snippet
that reverses the characters of a string:
In the first code example, the compiler cannot infer what the type of `x` should
be: `Vec<char>` and `String` are both suitable candidates. To specify which type
to use, you can use a type annotation on `x`:
```
let x: Vec<char> = "hello".chars().rev().collect();
```
It is not necessary to annotate the full type. Once the ambiguity is resolved,
the compiler can infer the rest:
```
let x: Vec<_> = "hello".chars().rev().collect();
```
Another way to provide the compiler with enough information, is to specify the
generic type parameter:
```
let x = "hello".chars().rev().collect::<Vec<char>>();
```
Again, you need not specify the full type if the compiler can infer it:
```
let x = "hello".chars().rev().collect::<Vec<_>>();
```
We can see a self-contained example below:
```compile_fail,E0283
struct Foo;
impl Into<u32> for Foo {
fn into(self) -> u32 { 1 }
}
let foo = Foo;
let bar: u32 = foo.into() * 1u32;
```
This error can be solved by adding type annotations that provide the missing
information to the compiler. In this case, the solution is to specify the
trait's type parameter:
```
struct Foo;
impl Into<u32> for Foo {
fn into(self) -> u32 { 1 }
}
let foo = Foo;
let bar: u32 = Into::<u32>::into(foo) * 1u32;
```
|