Skip to content

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

Description

@rxdiscovery

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions