Warning
This post was published 36 days ago. The information described in this article may have changed.
I have following minimal reproducible example (see also on playground):
pub struct Bar {
value: u32,
}
pub struct Foo {
pub bars: Vec<Bar>,
}
impl Foo {
pub fn new(bar: Bar) -> Self {
let mut bars = vec![];
if let Some(_) = bars.iter().find(|&item| item.value == bar.value) {
unreachable!();
}
bars.push(bar);
Self { bars }
}
}
When running cargo check
this fails to compile with following error:
Checking type-annotation-mre v0.1.0 (/home/akrauze/scratch/type-annotation-mre)
error[E0282]: type annotations needed for `Vec<_>`
--> src/lib.rs:11:13
|
11 | let mut bars = vec![];
| ^^^^^^^^
12 |
13 | if let Some(_) = bars.iter().find(|&item| item.value == bar.value) {
| ---------- type must be known at this point
|
help: consider giving `bars` an explicit type, where the type for type parameter `T` is specified
|
11 | let mut bars: Vec<_> = vec![];
| ++++++++
For more information about this error, try `rustc --explain E0282`.
error: could not compile `type-annotation-mre` (lib) due to 1 previous error
I find this very odd, because:
bars
thanks to bars.push(bar)
callrust-analyzer
shows correct types inlineI've tried running this with a couple of rust versions and editions, but the only things that changed were wording of error message.
Is this known limitation of the inference system in the compiler? I don't recall encountering anything similar in the past. If so, is it technically solvable (I suspect it is since rust-analyzer
can infer types properly) and is it planned in the future?
Or is it some regression/bug in the compiler that should be reported?
1 post - 1 participant
🏷️ rust_feed