How to return mapping list in Solidity? (Ethereum contract)

余生长醉 提交于 2019-12-06 17:18:02

问题


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?


回答1:


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.




回答2:


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.




回答3:


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;



来源:https://stackoverflow.com/questions/37606839/how-to-return-mapping-list-in-solidity-ethereum-contract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!