18

I want to make simple smart contract that has a list, can set item, and can get the list.

Code in solidity:

contract lister {
    mapping(int => string) list;
    int id = 0;

    function getList() returns ( /*HERE*/ ) {
        return list;
    }

    function setItemToList(string str) {
        list[id] = str;
        id++;
    }
}

I want to make getList() return the list, but return type is not compatible. How can I do that?

6londe
  • 366
  • 1
  • 6
  • 16

3 Answers3

19

Bulk access to lists/arrays/etc is painful in Solidity. You rarely see it in contracts. In your case, a possible solution is to provide a function to access one item, using its index, and to let the caller loops from 0 to id.

bortzmeyer
  • 30,796
  • 10
  • 61
  • 89
  • 4
    I'm just familiarizing myself with Solidity, but this is astonishing to me. How can any useful application be built? Are we supposed to _actually_ persist data somewhere else (in a non-ethereum app) and use dapps to interact with it and verify data integrity? – imnotquitejack Jan 05 '18 at 14:55
  • I believe the answer to this question is yes. In fact you can see which sites do this since they will be accessible without metamask installed. – jlansey Mar 26 '18 at 15:23
2

You can change the visibility of your variable list, insert public and it will possible to access this by getList.

mapping(int => string) public list;

HLeite
  • 37
  • 6
  • 2
    you should not do this. This makes map available to any one. So they can access the map without knowing key values. – e.k May 21 '18 at 14:54
1

With mappings, keys are not stored and the values can not be iterated upon, so they are really only good for single-value lookups. In the example you provide, it may be a better choice to use an array.

On the other hand, if you use an array and need to do a search on it (loop through all items), you need to be careful because if there are too many items in your array, it could end up costing a considerable amount of gas to call the function.

Alex
  • 135
  • 2
  • 13