0

For example,

struct somestruct {
        uint someuint;
        mapping(address=>uint) somemapping;
    }


arrayofsomestruct[] public _arrayofsomestruct;

The getter function automatically created for _arrayofsomestruct seems to return someuint in the array, but not the mapping values? Is an additional getter function required to retrieve the values in somemapping?

1 Answer 1

1

In your case you can use a getter function where you retrieve all values about specific struct inside array. See this smart contract:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;

contract RetrieveMappingValuesFromStructArray {
    struct somestruct {
        uint someuint;
        mapping(address=>uint) somemapping;
    }

    somestruct[] public _arrayofsomestruct;

    function setStruct(uint _firstValue, address _address,  uint _secondValue) public {
        somestruct storage someStruct = _arrayofsomestruct.push();
        someStruct.someuint = _firstValue;
        someStruct.somemapping[_address] = _secondValue;
    }

    function getStruct(uint index, address _address) external view returns(uint someuint, uint somemapping) {
        return (_arrayofsomestruct[index].someuint, _arrayofsomestruct[index].somemapping[_address]);
    }

}
2
  • Didn't expect such a detailed answer, thank you. BTW, without the getter function in this contract, can other contract get the mapping values of this contract through a getter function? If the array is accessible to the other contract.
    – frt132
    Commented Apr 17, 2022 at 18:12
  • You'll have ever to create a getter function in other contract to access into keys and values mapping. Commented Apr 18, 2022 at 21:44

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.