Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: A Type Inference Failure Edge Case?
I know that Rust can't always infer type information, especially if there is not enough information to resolve generic types, which makes complete sense. However, I was working on a project, and I came across this scenario where Rust couldn't resolve the generic types of a HashMap. This seemed surprising, because there are multiple places where the compiler could infer it, but just wasn't strong enough.
Code example below:
use std::collections::HashMap;
fn main() {
// Dummy code to compile
handle_selection(vec![])
}
fn handle_selection(
query: Vec<(u8, u8)>,
) {
// HashMap<_, _>
let mut board_map: HashMap<u8, Vec<u8>> = HashMap::new();
for (selection_id, slot_id) in query.iter() {
if let Some(selections) = board_map.get_mut(slot_id) {
selections.push(*selection_id);
} else {
board_map.insert(*slot_id, vec![*selection_id]);
}
}
eprintln!("{:?}", GameBoard::removals(board_map))
}
pub struct GameBoard;
impl GameBoard {
pub fn removals(board: HashMap<u8, Vec<u8>>) -> Vec<(u8, u8)> {
todo!("This is not relevant right now!")
}
}
The error specifically is:
error[E0282]: type annotations needed for `HashMap<_, _>`
--> src/main.rs:12:9
|
12 | let mut board_map = HashMap::new();
| ^^^^^^^^^^^^^
...
16 | selections.push(*selection_id);
| ---- type must be known at this point
|
help: consider giving `board_map` an explicit type, where the type for type parameter `V` is specified
|
12 | let mut board_map: HashMap<K, V> = HashMap::new();
| +++++++++++++++
I guess it makes sense how the type inference would struggle with this example. However, with a stronger type inference, after failing to resolve the type from line 16, couldn't Rust look at line 18 to figure out the type of selections
through the .insert(...)
, or infer the HashMap's type on line 22 with the GameBoard::removals
function call?
In other words, is this a case where the type inference isn't "strong enough", or is it just fundamentally wrong for the compiler to try to infer the type in this scenario.
Personally, my intuition leads me to believe it just isn't strong enough, but I could just be missing some underlying issues...
4 posts - 3 participants
🏷️ rust_feed