[Ethereum] How to return multiple strings from a contract function

contract-designcontract-developmentcontract-invocationsoliditystring

In solidity it's obvious how to get a single string returned from a function. But, I'd like to have the smart contract return multiple string values. Is there a way to do this?

Best Answer

There are a few types of string values that you may be referring to.

  • bytes1 - bytes32: fixed size.
  • bytes or string: dynamically sized.

Solidity supports functions with multiple return values.

contract MultiReturner {
    function getData() constant returns (bytes32, bytes32) {
        bytes32 a = "abcd";
        bytes32 b = "wxyz";
        return (a, b);
    }

    function getDynamicData() constant returns (bytes, bytes) {
        bytes a;
        a.push('a');
        a.push('b');
        a.push('c');
        bytes b;
        b.push('x');
        b.push('y');
        b.push('z');
        return (a, b);
    }
}

You can do the same with bytes or string but with the limitation that solidity does not support returning dynamically sized values to other functions. This means that you would be able to use the getData function from within another contract and retrieve the return values but you would not be able to retrieve the return values from getDynamicData from within a contract.

contract UsesMultiReturner {
    function doIt() {
        mr = MultiReturner(0x1234);

        // this will work
        var (a, b) = mr.getData();

        // this won't work
        var (a, b) = mr.getDynamicData();
    }
}

You can however retrieve the return values from both getData and getDynamicData when call from outside of the blockchain.

Related Topic