1
pragma solidity ^0.4.24;

contract User {
    mapping(uint=>address) addresses;
    uint addressRegistryCount;   

    function set(address userAddress) public {
        addresses[addressRegistryCount] = userAddress;
        addressRegistryCount++;
    }

    function get(address userAddress) public view returns (uint) {
        for (uint i = 0; i <= addressRegistryCount; i++) {
            if(addresses[i] == userAddress)
                return i;
        }
    }

    /*function getAll() {

    }*/
}

In this contract I have a function called getAll. Inside that function I´m trying to return the full mapping of users. How can I make that?

  • If you want to fetch it from the off-chain, then just add public before addresses, and you've got yourself a "getAll" function (which you can invoke from the off-chain via addresses()). – goodvibration Jan 15 at 9:20
  • @goodvibration Adding the public identifier doesn't result in a getAll function. It gives you a public function which takes index as input and returns only one element of mapping. – saman.shahmohamadi Jan 15 at 9:36
2

You can't return a mapping directly. What you can do is to make an array and add all address values that is stored in the addresses mapping to it. Then return that array.

function getAll() public view returns (address[] memory){
    address[] memory ret = new address[](addressRegistryCount);
    for (uint i = 0; i < addressRegistryCount; i++) {
        ret[i] = addresses[i];
    }
    return ret;
}
  • You actually can return a mapping, so long as it maps types of fixed length (and in the example above, uint and address are such). – goodvibration Jan 15 at 9:17
  • Could you provide an example code? – saman.shahmohamadi Jan 15 at 9:22
  • 1
    See my comment to the question. – goodvibration Jan 15 at 9:25
  • Works fine thx bouth ;D – UnexpectedCharacter Jan 15 at 12:55
  • Your're welcome ;-) – saman.shahmohamadi Jan 15 at 12:59

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.