Unable to understand HashMap issue

Code

lazy_static! {
    static ref PATHS: HashMap<String, String> = HashMap::new();
}

pub fn add (path: Path) {
    PATHS.insert("mid".to_string(), path);
}

Error

cannot borrow data in a dereference of `PATHS` as mutable
trait `DerefMut` is required to modify through a dereference, but it is not implemented for `PATHS`

This code cannot exist in Rust since it seems to me that PATHS is a global and globals cannot be declared with let in Rust.

I have updated the code.
Sorry I am new to rust

Globals in Rust can't be safely mutably borrowed. You either have to redesign your application to avoid global state, or use some type allowing internal mutation (example: Mutex). I recommand you go with the first approach : avoid global state.

2 Likes

Yes, so you see that PATHS is not declared as mut and cannot be borrowed as mut.
If you want mutability, you have to wrap it in a type that gives you interior mutability. For example a Mutex.

Thank you so much.
A small example will be very helpful.

Something like:

lazy_static! {
    static ref PATHS: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
}

pub fn add (path: Path) {
    let paths = PATHS.lock();
    paths.insert("mid".to_string(), path);
}
1 Like

Awesome
Thank you so much

Hi, Thank you for your reply.

I was unable to find any solution to avoid global variable.
Can you please give me some example from this snippet so that I can avoid it.

For example, in the context calling add :

// you currently have something like :
add(value);
// instead do :
let mut map = HashMap::new();
add(&mut map, value);

Avoiding global state is generally very simple.

2 Likes

The typical strategy is to pass the shared state to each function as an argument. You can also store the thing in a struct so it is available as self.whatever.

If it starts feeling cumbersome to pass all these shared objects around via arguments I normally interpret that as my code saying "maybe you are sharing too much state here and should refactor your code to be less coupled?"

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.