Type inference failure when accessing a value before its type is resolved
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Hello,
I noticed that the compiler / Rust Analyzer behaves unexpectedly.
Type inference fails if a value is accessed before the point where its type is ultimately inferred, as if the inference context is lost.
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct NodeMoonStatsDTO {
pub node_id: String,
pub uptime: u64,
//.....
}
type SharedState = Arc<HashMap<String, HashMap<String, NodeMoonStatsDTO>>>;
pub struct SystemMonitorService {
pub live_nodes_moon_stats: SharedState,
}
impl SystemMonitorService {
pub fn get_node_moon_stats(&self, cluster_id: &str) -> Option<Vec<NodeMoonStatsDTO>> {
let result = self
.live_nodes_moon_stats
.get(cluster_id)
.map(|stats| stats.iter().map(|(_, value)| value.clone()).collect());
let r = result.clone().unwrap();
//println!("{:?}", r);
for n in r {
println!("{}", n.node_id);
}
result
}
}
Output :
Compiling playground v0.0.1 (/playground)
error[E0282]: type annotations needed
--> src/lib.rs:28:28
|
28 | println!("{}", n.node_id);
| ^ cannot infer type
For more information about this error, try `rustc --explain E0282`.
error: could not compile `playground` (lib) due to 1 previous error
Adding the following:
for n in r {
println!("{}", n.node_id);
}
breaks type inference.
Discussion link here for more details :
Thank you in advance..
rustup: 1.29.0
rustc : 1.95.0
rust-analyzer: 0.3.2887
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the failure in the linked Rust Playground using src/lib.rs, comparing the example with and without the loop that accesses n.node_id. Start by determining whether the behavior belongs to rustc or rust-analyzer, then trace how collect(), result.clone(), and the later field access affect type inference. Done means a minimized regression case and a confirmed fix or clarified expected behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100