Advice on sharing HashMap between functions

I'm learning how to use Rocket, but I don't believe my question is specific to Rocket.
I want to define several routes that share access to a HashMap.
You can see my code here: rust-rocket-demo/ at master · mvolkmann/rust-rocket-demo · GitHub

When I enter cargo clippy I get lots of errors that say "can't capture dynamic environment in a fn item".
I understand why it says this. Functions are not closures, so my functions cannot see dog_map.

But what is the best way to handle this? I could try changing all my functions that want to access dog_map to be closures, but then maybe the Rocket attributes like get and post won't work.

Rocket's State type and Rocket::manage method are designed to deal with this: State - Rocket Programming Guide

In Rust programs more generally (beyond Rocket), you could use closures as you suggested, or you could make the state global, often with the help of once_cell or lazy_static, or you could pass the state through arguments, possibly by making all your functions into methods of a struct that contains all the state.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.