I was reading a tutorial on a medium about how to return an array of structs. This is the code they have for doing it.

pragma solidity ^0.4.13;

contract Project
    struct Person {
        address addr;
        uint funds;

    Person[] people;

    function getPeople(uint[] indexes)
        returns (address[], uint[])
        address[] memory addrs = new address[](indexes.length);
        uint[]    memory funds = new uint[](indexes.length);

        for (uint i = 0; i < indexes.length; i++) {
            Person storage person = people[indexes[i]];
            addrs[i] = person.addr;
            funds[i] = person.funds;

        return (addrs, funds);

The uint[] index argument however makes no sense to me. Can someone please explain what it is and what it does?

  • Do you mean the uint[] indexes argument? – valkn0t Jul 17 '18 at 13:54
  • Yep, that's what I meant. @valkn0t – user3078335 Jul 17 '18 at 13:55

uint[] indexes is used to access the data of people located at the indices passed to the function, to build an array of structs to return.

For example: if there were 100 Person stored in the contract, and we wanted an array of just the Person's stored at [1, 2, 3], we pass that array as uint[] indexes and receive the addresses and funds located at people[1], people[2], and people[3].

  • Thanks for your answer. It makes sense. What it if I wanted to return every person in people. [1... people.length] ? Still a newbie to solidity :) – user3078335 Jul 17 '18 at 14:05
  • If you wanted to return the entire array you could simply remove/ignore the argument uint[] indexes and loop over people[] til people.length, putting the addresses and funds into the correct arrays, and returning them like how it's implemented in the code above. Also just to be clear: solidity is simply a Javascript-esque language used to write and compile smart contracts; these questions are more Javascript questions than Solidity. If you have further questions about things like loops and arrays and such, I'd suggest researching Javascript code before Solidity. – valkn0t Jul 17 '18 at 14:11
  • ah! gotcha! I will try that approach. Thank you very much for your help!! – user3078335 Jul 17 '18 at 14:13
  • I will do that. Very new to javascript as well. Thanks for your help. – user3078335 Jul 17 '18 at 14:14

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.