I have a mapping in solidity. How can I check if a key exist in this mapping. Mapping returns the data type default value if I try to access a non existent key.
Is there any graceful way to achieve the same.
I have a mapping in solidity. How can I check if a key exist in this mapping. Mapping returns the data type default value if I try to access a non existent key.
Is there any graceful way to achieve the same.
There is no way to do it, because if value didn't set, there will be default value (false, 0, etc.). The best way out is to check that the value is different from the default value
There is no other other way to do this than just check if the key in question has a value initialized.
If you need more than that (e.g. to be able to keep track of which keys have values set, count them, list them, etc.) then a fairly common pattern is to maintain an array alongside the mapping, containing the known keys.
That way, when all you want is the value (or to check its existence), you can query the mapping, which is very gas efficient. When you want to do something with the set of known keys, you can interact with the array.