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.
Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type.
We can create a function remove() that will take an array's index as an argument. Then the function will set the index argument to the last element in the array. Simply, we will shift the index argument over the last element of the array. Then we will remove the last element by using the pop() method.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With