Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solidity setting a mapping to empty

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

like image 634
antonis Avatar asked Dec 31 '17 21:12

antonis


People also ask

How do you clear a map in Solidity?

You cannot clear all mapping values without specificy the key. Thus, Solidity doesn't know the keys of the mapping. Since the keys are arbitrary and not stored along, the only way to delete values is to know the key for each stored value. Your remove() function is correct to clear the values of a specific mapping key.

How do you initialize empty mapping in Solidity?

You can rewrite your code like this: tests[0] = Test({ id: 0 }); Solidity will make votes an empty mapping by default. Btw, there's also a typo in your code: should be tests[0] instead of test[0] .

Can you iterate through a mapping in Solidity?

Can you iterate over a mapping Solidity? In Solidity, you can define a mapping. The mapping holds the key-value pairs. However, there is no way to iterate over the mapping entries in Solidity.


2 Answers

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.

like image 110
Adam Kipnis Avatar answered Oct 16 '22 17:10

Adam Kipnis


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
like image 39
BananaNeil Avatar answered Oct 16 '22 17:10

BananaNeil