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.

1 Answer 1

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.

2
  • Can I use Event to list the addresses?
    – alper
    Commented Jan 20, 2017 at 15:15
  • You can emit an event at every addition to the mapping, yes. Note that this can't be read back by the contract, and it probably won't be light client friendly. Commented Jan 20, 2017 at 21:03

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.