0

Let's say I have a custom struct and a mapping:

struct MyStruct {
    uint var1
    string var2
    bool var3
}

mapping(address => MyStruct) myMapping;

If I did this:

//.......
MyStruct elem1 = myMapping[addr1];

I wouldn't be able to know whether elem1 really exists in myMapping, because it would return an element anyway. If it wasn't present, it'd return the one with all the fields initialized with the default values, right?

What's the solution for that?

1 Answer 1

1

We can do this by creating a field in the struct that is a bool value and on creating the item we set it to true, otherwise it will stay at the default as false. This looks something like this.

contract Solution {
    struct MyStruct {
        uint var1;
        string var2;
        bool exists;

    }

    mapping(address => MyStruct) myMapping;


    function doesExist(address _check) public view returns(bool) {
        MyStruct memory obj = myMapping[_check];
        return obj.exists;
    }

    function addMapping(address _toAdd) public {
        MyStruct memory toAdd = MyStruct({
            var1: 1,
            var2: "hello world",
            exists: true
        });

        myMapping[_toAdd] = toAdd;

    }
}
2
  • is that the only way?
    – Okkun
    Jan 8, 2022 at 12:46
  • its the simplest way i can think of @Okkun
    – nemo
    Jan 8, 2022 at 12:49

Your Answer

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

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