Steve Brown
Steve Brown

Reputation: 449

Deleting mapping from mapping in Solidity

I have something like this:

mapping (address => mapping(string => uint)) m_Map;

It can be accessed as m_Map[strCampaignName][addrRecipient], campaign can have multiple recipients...

Now at some point (ICO failed), I need to remove that campaign with all recipients. I don't think a simple delete m_Map[strCampaignName] will work. If I use m_Map[strCampaignName] = null, I think data will not be deleted. If I iterate through a list of all recipients, I will run out of gas.

How should this situation be handled? Min: I want m_Map[strCampaignName] to be empty, Max: I want to stop wasting memory on it.

Upvotes: 11

Views: 18224

Answers (2)

Melih
Melih

Reputation: 473

If you have all the addrRecipient of the mapping

delete m_Map[strCampaignName][addrRecipient];

works.

Upvotes: 1

Adam Kipnis
Adam Kipnis

Reputation: 11001

As you stated, you can't delete a mapping in Solidity. The only way to "clear" the data is to iterate through the keys (using a separate array that stores the keys) and delete the individual elements. However, you're correct to be concerned about the cost...Depending on the size of the mapping, you could run into gas consumption issues.

A common approach to work around this is to use a struct in your mapping with a soft delete:

struct DataStruct {
  mapping(string => uint) _data;
  bool _isDeleted;
}

mapping(address => DataStruct) m_Map;

Now, deleting an entry just requires you to set the flag: m_Map[someAddr]._isDeleted = true;

Upvotes: 4

Related Questions