Is it possible to traverse a mapping?[email protected] Member Posts: 5
I've got a mapping with a meaningful, non-numeric key.
I also need to run through the mapping and extract all the entries (without knowing the keys).
Is there an easy way to traverse the mapping (like an Iterator in java)?

Thank you.



  • bluedropletbluedroplet Member Posts: 8
    I think at the moment the array / mapping handling is not as mature as it is in other languages.

    There is no foreach(), no isset(), no count(), and you cannot add a new item to an array without specifying the index.

    It's also not possible to pass nested arrays / strings as arguments to external functions yet.

    This means it is currently considerably harder to write a contract than one would expect.

    These problems can be alleviated to some extend by doing less in the contract, e.g. the automatic getter functions on public variables can be used to retrieve the state in its entirety and then do processing in the calling app.
  • chrisethchriseth Member Posts: 170 ✭✭✭
    By design, it is not possible to retrieve the keys of a mapping or iterate over its values. Mappings and also arrays to some extent are still low-level data structures. They will be greatly expanded as soon as we have library support and can provide a standard library of high-level data structures that are provably correct.
    Until we have that, my advice would be to use a mapping key -> index and put your values into an array.

    Concerning @bluedroplet's "doing less in the contract" comment: I would recommend to only do the absolute essential in the contract. Everything that can be done in the app should be done in the app to save gas.
  • bluedropletbluedroplet Member Posts: 8
    @chriseth I was really referring to calls that are not transactions, i.e. there is no cost. In this situation it might normally make sense to do more in the contract instead of pulling all the data out and doing processing externally. However because of the immaturity of the eco-system it might be easier to not do this for the time being.
  • chrisethchriseth Member Posts: 170 ✭✭✭
    edited July 2015
    Yes, this case you are right, but you still have the cost of storing the code.
    We are currently thinking whether it might be possible to get rid of these costs by either letting the compiler emit javascript code to access in-contract data (which will probably be rather slow due to the json-rpc-latency) or storing auxiliary evm code which is executed in a callcode fashion and not stored on the blockchain.
  • bluedropletbluedroplet Member Posts: 8
    Thanks @chriseth that's very interesting!
Sign In or Register to comment.