Search code examples
blockchainethereumsolidityevm

return array of type string in solidity


if we have a mapping that is like => mapping(uint => string[])

and we want create a function that get a number and return all strings that are related to that number

how should I declare it in order to return that string array of mapping??

I want to return the string array of mapping in another function


Solution

  • You can see this example of smart contract for your case:

    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8;
    
    contract Test {
        mapping(uint => string[]) mString;
        
        // Adding elements inside mapping
        function fillMapping(uint key, string[] memory values) public {
            mString[key] = values;
        }
    
        // Getter method for retrieve values from mapping, querying for a specific key 
        function getValueFromMapping(uint key) public view returns(string[] memory) {
            return mString[key];
        }
        
        // Using mapping values in other function
        function useMappingInOtherFunction(uint key) public {
            string[] memory stringValues = getValueFromMapping(key);
            // your logic
            // ...
            //
        }
        
    }