Reputation: 133
I am trying to create a smart contract using Solidity 0.4.4.
I was wondering if there is a way to set a mapping with some values already entered to an empty one?
For example:
This initailises a new mappping
mapping (uint => uint) map;
Here I add some values
map[0] = 1;
map[1] = 2;
How can I set the map back to empty without iterating through all the keys?
I have tried delete but my contract does not compile
Upvotes: 12
Views: 13763
Reputation: 1
I think there is a hacky solution to do this. But it requires adding an additional array to store keys of mapping. So I don't think it's a good solution and it's better to create a new contract than this solution. :) If you really want to reset mapping, please refer to my solution.
mapping(address => FarmingData) public farmingData;
address[] public farmers;
function addFarmer() external {
farmers.push(user);
FarmingData storage data = farmingData[user];
// ...
}
function _endFarmingPeriod() internal {
// Reset farming data for each user
for (uint i = 0; i < farmers.length; ) {
address user = farmers[i];
delete farmingData[user];
unchecked {
++i;
}
}
delete farmers; // Reset the list of farmers
}
However, if the address array contains a large amount of data, it will require a significant gas fee, so this method is not recommended for large arrays.
Upvotes: 0
Reputation: 10762
I believe there is another way to handle this problem.
If you define your mapping with a second key, you can increment that key to essentially reset your mapping.
For example, if you wanted to your mapping to reset every year, you could define it like this:
uint256 private _year = 2021;
mapping(uint256 => mapping(address => uint256)) private _yearlyBalances;
Adding and retrieving values works just like normal, with an extra key:
_yearlyBalances[_year][0x9101910191019101919] = 1;
_yearlyBalances[_year][0x8101810181018101818] = 2;
When it's time to reset everything, you just call
_year += 1
Upvotes: 8
Reputation: 10971
Unfortunately, you can't. See the Solidity documentation for details on the reasons why. Your only option is to iterate through the keys.
If you don't know your set of keys ahead of time, you'll have to keep the keys in a separate array inside your contract.
Upvotes: 10