0

I have a function that inside have a if-else.My idea is to return a couple of parameters if the conditions is fulfilled or one string if the condition is not fulfilled . The problem is that in the function creation I put to returns more than one parameter.

function getOrigin (uint _id) isOwner public returns (address, string, uint32, uint16)
{
    if (travels[_id].clientAddress == msg.sender)
        return (travels[_id].clientAddress, travels[_id].originAirportName ,travels[_id].originTime ,travels[_id].originBagWeight);
    else 
        return (msg.sender,"Acceso prohibido",3,3);
}

At the moment I load fake values to the return. But if I want just to return the second parameter of the else return?

  • 1
    You can't. You cannot return a dynamic amount of values. – Florian Castelain Nov 26 '18 at 9:45
1

You must assign dynamic variables to separate variables like this:

function getOrigin (uint _id) isOwner public returns (address, string, uint32, uint16)
{
    if (travels[_id].clientAddress == msg.sender) {
        address a = travels[_id].clientAddress;
        string memory b = travels[_id].originAirportName;
        uint32 c = travels[_id].originTime;
        uint16 d = travels[_id].originBagWeight;
        return (a, b, c, d);
    }
    else 
        return (msg.sender,"Acceso prohibido",3,3);
}

Note: Only assigning b variable is necessary. Others are for butifying the code.

| improve this answer | |
  • 1
    why you use memory for just the b value? – UnexpectedCharacter Nov 26 '18 at 10:32
  • because default is storage and here no need to storage. – Alireza Zojaji Nov 26 '18 at 11:02
  • oquei thx. But just one question why i have to recover the values into variables?? It´s not better to return directly from the struct that i have data no (travels[_id].clientAddress)??? cheaper gas cost?? – UnexpectedCharacter Nov 26 '18 at 11:14
  • This is because your defined struct is meaningful only interior of your contract not out of it. So if you define your contract as internal, you can use a struct as the return parameter. – Alireza Zojaji Nov 26 '18 at 13:54

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.