Replacing/moving HashMap

I have an application that contains a struct which contains a HashMap. Once I've read a number of parameters from the network (and put them into the HashMap) I need to do two things (note that the order here does not make sense):

  • Return the HashMap
  • Clear the internal HashMap to prepare for receiving the next one.

I'm currently cloning the internal HashMap in order to return the clone, then I call .clear() to clear the internal HashMap to prepare for the next one.

What I - in theory - want to do is "move" the HashMap out of the struct and create a new (empty) HashMap in its place (i.e. "swap" the old one with a new (empty) one). My gut feeling tells me this is impossible, but I gotta ask if there some way to do it.

This is what mem::take does.

1 Like

Ah! The Default trait -- of course!

1 Like

There is also std::mem::replace, for when you don't want to set it to the default value, or can't because the type doesn't implement Default.

2 Likes

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.