rust-lang / rust-lang/rust

Type inference failure when accessing a value before its type is resolved

Open
#156,340 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug needs-triage
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.

Here is the playground link.

Discussion link here for more details :

https://internals.rust-lang.org/t/type-inference-breaks-in-rust-analyzer-when-a-loop-is-added-between-inference-points/24232

Thank you in advance..

rustup: 1.29.0 
rustc : 1.95.0
rust-analyzer: 0.3.2887

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.