Cannot Infer Type of Vec of `mpsc::Sender<>`

⚓ rust    📅 2025-06-11    👤 surdeus    👁️ 2      

surdeus

I realize this question or similar questions probably gets asked a lot, but I think this one is a bit unique.

I am attempting to pass messages between threads using mpsc channels and in order to send data from the controller thread back to each requester thread, I use a vector of mpsc::Senders to hold a unique sender for each thread.

I am getting an error on the first match branch, specifically on the section tx_channels[thread_id] which simply says cannot infer type. No other suggestions from clippy or cargo.

The second match branch is not erroring. I can't tell if this is because it is working, or because the first match branch is breaking things so badly that the compiler can't continue.

As far as I can tell, this should be Sender<ThreadResponse> as defined in the let tx_channels = ... line, but the compiler is not picking this up.

I am also at a loss as to how to tell the compiler what type it should be, as tx_channels[thread_id]::<mpsc::Sender<ThreadResponse>>.send(ThreadResponse::AllRecipes(recipes.clone())) (Turbofish syntax) just gets me an error about how the compiler is expecting a different symbol.

    // TODO: add this into the config file
    let num_threads: usize = 4;
    let mut join_guards = Vec::with_capacity(num_threads+1);
    let mut tx_channels: Vec<mpsc::Sender<ThreadResponse>> = Vec::with_capacity(num_threads);

    // spawn data owner thread
    join_guards.push(thread::spawn(move || {
        let mut recipes = recipes.clone();
        loop {
            // TODO: fix usage of unwrap here
           let (thread_id, message) = rx.recv().unwrap();
           match message {
                ThreadMessage::AllRecipes => tx_channels[thread_id].send(ThreadResponse::AllRecipes(recipes.clone())),
                // TODO: properly handle the Option of HashMap.get() rather than unwrapping
                ThreadMessage::RecipeRO(recipe_id) => tx_channels[thread_id].send(ThreadResponse::Recipe(recipes.get(&recipe_id).unwrap().clone())),
                ThreadMessage::RecipeRW(recipe_id) => todo!()
           }
        }
    }
            
            ));

This is from Line 139 in the linked repo if you need more context.

I apologize for the formatting mess, since this isn't compiling, I can't get rustfmt to run.

Appreciate any assistance here.

12 posts - 4 participants

Read full topic

🏷️ rust_feed