0

I have seen that many posts do recommend using default values to check whether a key in a mapping exists.

For example, if i have a mapping

struct Holder {
    uint256 Value1,
    uint256 Value2
}

mapping(uint256 => Holder) public HolderMapping;

Holder storage firstHolder;
firstHolder.Value1 = 1;
firstHolder.Value2 = 1;

HolderMapping[1] = firstHolder

Now if i want to test whether some key exists, is it a safe method to check whether Value1 and Value2 are default values inside the key? like checking if HolderMapping[2] has Value1 and Value2 == 0?

Or are there safer methods? I hope my questions clear, thanks!

1 Answer 1

1

you'd have to make that call on a case by case basis as it depends on the nature of the data and logic

for something like mapping(string => uint) bookPages 0 would be a non-sensical number, so could be a test of whether it exists.

if the default value is a valid value, then it's not a safe way to check. e.g. for mapping(address => uint) balances it wouldn't be safe as a balance of zero is a valid value, so you couldn't be sure that the mapping didn't exist ... but you might decide in this case that it doesn't matter why it is zero i.e. because it didn't exist or is just a 0 balance.

if it's something you need to know you could have an additional mapping to keep track of it e.g. mapping(address => bool) accountExists

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.