I've written a smart contract in which if the same address is entered again. Then it will be stored on address and index value. Now I want to return the data from 1 to 10 at a time.

The code is like

contract Bar{

    struct Foo{
        uint x;
    mapping(uint => Foo[]) foo;

    function add(uint id, uint _x) public {

    function get(uint id, uint index) public returns(uint){
        return foo[id][index].x;

can somebody help me with this?

  • It's currently not possible to return an array of comlex data types (like structs and arrays) from a function in Solidity. It is however possible to return an array of simple data types, like uint[]. In your specific case, you could just return each Foo's x in an array. But I have a feeling you want to be able to do this with more complex structs – Henk Aug 7 '18 at 8:06

Unsure of what exactly you want since your get function only returns one index. Also mark your get() as a view method - since it doesn't alter the state of your contract. A view method costs no gas. So you can have for loops too. Thus the method to get first 10 items for a id would be:

function get10Items(uint id) public view returns (uint[10]) {
    uint[10] memory array = [0,0,0,0,0,0,0,0,0,0];
    for (uint i=0; i<10; i++) {
        array[i] = foo[id][i].x;
    return array;

You can also add a checker in case foo[id] is an array of lesser than 10 items

  • Thanks Jaime , I tried that way. But it's giving me an error. Can you please help me with the function which will bse best suited if I wish to return the complete records of index 0 to index 10 or soo. – shrey bhardwaj Aug 7 '18 at 8:43
  • It's Rahul actually. What is the error? Are you sure that food[id] actually has 10 elements? – Rahul Kothari Aug 7 '18 at 9:03
  • I'm sorry Rahul. Actually I just want the total number of index value data. It could be 2,3 or 10. Depend on the user. How much data user entered on the particular address( public key). When the user call the function - function get10Items(as you mentioned above). Will return the total number of index value data. Wether it the index value is 10 or 20. if the index value is 10 then the data of 10 index (total, means from 1,2,3 ....10 will return). This is how I wanted to make it work. Please help me over with this. – shrey bhardwaj Aug 7 '18 at 9:10

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.