Mapping iterations

While we are talking about search logic, let me open a parenthesis about mappings to answer a recurring question.

Are mappings iterable? The answer is no, they aren’t.

Currently Solidity doesn’t support iterating a mapping, as they don’t have a fixed length (number of non-null key-values entries). However, you can use an auxiliary array and structure in which you store the keys to your mapping to tie each element to its key. Using this pattern, the IterableMapping library was built by Solidity developers to iterate over the mapping keys. Its code is available in the following GitHub repository: https://github.com/ethereum/dapp-bin/blob/master/library/iterable_mapping.sol.

Get Blockchain By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.