Published on

Attempting to Return Arrays and Structs in Solidity Functions


Today I was working on adding additional functions to a Solidity contract. I needed one function to return a struct and another to return an array.

This is something that is fairly routine in most languages but this is not too trivial in Solidity.

In the case where a struct needs to be returned this is luckily fairly easy to work around with Solidity supporting multiple return values. For example if I have the following Solidity struct:

struct Person {
   string name;
   string surname;
   uint age;

Then to return this I would do something like:

function getPerson(bytes32 personHash) public view returns (string, string, uint){
 Person memory person = people[personHash];

 return (, person.surname, person.age);

If you coded your DApp using web3 it is actually very easy to consume data from this contract method. When calling this contract function an array of the return values is returned. If you combine this with ES6's array destructuring you get something very usable:

const [name, surname, age] = yourContract.getPerson(hashForJohn)

In the above you can call the array parameters whatever you want. The array contains the return values in the order that they were returned in the contract. The key thing is that you name each positional element in the array a name that makes sense.

Returning an array in Solidity on the other hand is not currently possible. There is an experimental array feature but this has still not been finalised and would not be a good idea to use as a result.

There are a bunch of hacky approaches like returning indices and then using that to query your data but this approach is ugly. Another approach is to make the array (you want accessible) public as Solidity automatically gives public variables getters. This only works if the array being exposed can be public (i.e no privacy concerns). Until this becomes a full blown feature the best would be to keep data off chain and use the blockchain more for random access of data and verifying that data has not been tampered with.