0

How can I return multiple value. If I get string ,it return the last value. How to get string ,its return multiple value?

pragma solidity ^0.8.0 ;

contract Simple {
    mapping(string => uint)  serialID;
    
    function set(string memory _id ,uint value_a ,uint value_b ,uint value_c ,uint value_d) public {
        serialID[_id] = value_a;
        serialID[_id] = value_b;
        serialID[_id] = value_c;
        serialID[_id] = value_d;
    }

    function get(string memory _id) public view returns(uint) {
        return serialID[_id];
    } 
}

2 Answers 2

0

In your set function you are updating the value of the same key : so it will only store the last value (you are replacing value_a with value_b, value_b with value_c and so on), because mapping will assing one key to one value . the function bellow do the same thing:

function set(string memory _id , uint value_d) public {

    serialID[_id] = value_d;

}

if you want to assing one key to mutiple value you should use a struct:

 struct Test{
       uint a;
       uint b;
       uint c;
       uint d;
   }
   mapping(string => Test) public serialID;
   function set(string memory _id){
      Test storage test = Test(1, 2, 3, 4);
      serialID[_id] = test;
   }
   
   function get(string memory _id) public view returns(uint, uint, uint, uint){

    return serialID[_id];
} 

i hope that helps, good luck !

0

Another solution for solve your issue is using uint[] array into mapping and change set function signature adding a unique uint array parameter.

In conclusion, your smart contract should be similar to this:

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

contract Simple {
    mapping(string => uint[]) serialID;
    
    function set(string memory _id, uint[] memory _values) public {
        serialID[_id] = _values;
    }

    function get(string memory _id) public view returns(uint[] memory) {
        return serialID[_id];
    } 
}

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.