1

Can we use tuple as mapping keys? For example:

mapping ((address, uint256) => uint256) myMapping;

If not, what's the closest workaround? Consider the two components of the tuple can go up to uint16.

EDIT

To be more explicit, I can think of two workarounds. The first is a mapping of mapping, though I don't know if it will lead to any additional computational costs than knowing that the two mappings are always used together.

The second is a fixed 2D array (since it goes up to uint16 I can just allocate a 65536 * 65535 array. But this seems to have the potential of allowing a lot of empty spaces (especially if we consider that the value of the mapping might be a struct). I'm guessing such a huge structure might have larger transaction fees comparing to the sparse representation (especially at the beginning where the grid is almost empty).

EDIT2

Originally I was asking with the following example, which was misleading and made ppl think that this was my actual question. I have updated my example (above) to avoid the confusion. For this particular case below, a comment to my question cleverly pointed out that we can convert two uint16 into one uint32 and avoid the tuple situation.

mapping ((uint16, uint16) => uint256) myMapping;
  • Why not just put the two together into a single uint32? E.g. (a, b) to (a << 16) + b. (You can split them apart similarly.) – smarx Jan 10 '18 at 1:13
  • The two uint16 is just an example, which happens to allow your workaround. But in general, as the title is asking, how do we deal with tuples. Note that the two component of a tuple might not share the same data type. – Roy Jan 10 '18 at 6:42
  • Let me change the uint16 in my question to something else to avoid misleading readers. – Roy Jan 10 '18 at 6:42
  • 1
    mapping(address => mapping(uint256 => uint256)) seems like the most natural thing to do. – smarx Jan 10 '18 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.