]>
Commit | Line | Data |
---|---|---|
60c5eb7d XL |
1 | This error occurs when the compiler is unable to unambiguously infer the |
2 | return type of a function or method which is generic on return type, such | |
3 | as the `collect` method for `Iterator`s. | |
4 | ||
5 | For example: | |
6 | ||
7 | ```compile_fail,E0284 | |
8 | fn foo() -> Result<bool, ()> { | |
9 | let results = [Ok(true), Ok(false), Err(())].iter().cloned(); | |
10 | let v: Vec<bool> = results.collect()?; | |
11 | // Do things with v... | |
12 | Ok(true) | |
13 | } | |
14 | ``` | |
15 | ||
16 | Here we have an iterator `results` over `Result<bool, ()>`. | |
17 | Hence, `results.collect()` can return any type implementing | |
18 | `FromIterator<Result<bool, ()>>`. On the other hand, the | |
19 | `?` operator can accept any type implementing `Try`. | |
20 | ||
21 | The author of this code probably wants `collect()` to return a | |
22 | `Result<Vec<bool>, ()>`, but the compiler can't be sure | |
23 | that there isn't another type `T` implementing both `Try` and | |
24 | `FromIterator<Result<bool, ()>>` in scope such that | |
25 | `T::Ok == Vec<bool>`. Hence, this code is ambiguous and an error | |
26 | is returned. | |
27 | ||
28 | To resolve this error, use a concrete type for the intermediate expression: | |
29 | ||
30 | ``` | |
31 | fn foo() -> Result<bool, ()> { | |
32 | let results = [Ok(true), Ok(false), Err(())].iter().cloned(); | |
33 | let v = { | |
34 | let temp: Result<Vec<bool>, ()> = results.collect(); | |
35 | temp? | |
36 | }; | |
37 | // Do things with v... | |
38 | Ok(true) | |
39 | } | |
40 | ``` | |
41 | ||
42 | Note that the type of `v` can now be inferred from the type of `temp`. |