0

I have a struct that has an array of addresses. When the address array is empty and I try to get index 0 I would expect it to return address(0), but instead it reverts. Any way around this?

struct KeyedMapAddressToBool {
  mapping(address => bool) data;
  mapping(address => uint) indices;
  address[] addresses;
}

function set(KeyedMapAddressToBool storage map, address key, bool value) public {
  map.data[key] = value;
  // THIS REVERTS
  address a = map.addresses[0];
}

EDIT:

I updated my struct to contain an exists mapping, but am wondering if there is another way. This works:

struct KeyedMapAddressToBool {
  mapping(address => bool) data;
  mapping(address => uint) indices;
  address[] addresses;
  mapping(address => bool) exists;
}

function set(KeyedMapAddressToBool storage map, address key, bool value) public {
  map.data[key] = value;
  if (map.exists[key] == false) {
    map.indices[key] = map.addresses.length;
    map.addresses.push(key);
    map.exists[key] = true;
  }
}
2

When a dynamic array has .length == 0 you can't access the first row to read or write because it doesn't exist. You can append to it with the push() method or increase with .length++.

map.addresses[0] would only run successfully if length is at least 1.

You may find some ideas to help organize contract state over here: Are there well-solved and simple storage patterns for Solidity?

Hope it helps.

  • Got it. Thank you. I added my solution to my question. I added an exists mapping. – pizza r0b Jan 25 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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