3

This answer shows that we can return all the addresses (from address[] public) as a single array of addresses:

function getAddresses() constant returns (address[]){
    return MemberAddresses;      
}

Instead of address[] public MemberAddresses; if we have mapping(address => uint) MemberAddresses;

contract AddressList {  
    mapping(address => uint) MemberAddresses;

    function registerAddress(uint var) { 
        MemberAddresses[msg.sender] = var;
    }  
}

[Q] Can we return all the addresses inside mapping, as a single array of addresses?

Thank you for your valuable time and help.

alper
  • 8,395
  • 11
  • 63
  • 152

1 Answers1

1

Unfortunately not. A mapping just matches a key to a value. It doesn't have a list of either per se.

However, there is a quick workaround. Just have both an array and a mapping. When you add a value to the mapping, add the address to the array. When you need the list, consult the array. When you need the value, consult the mapping.

That said, this pattern may start to fail if there's no limit to the array's growth. A mapping can be arbitrarily large, but if you're returning the entire array it will use more gas the more addresses that are on it. Depending on what scale you're working at, you may have to consider architecture further.

Matthew Schmidt
  • 7,290
  • 1
  • 24
  • 35