[Ethereum] Is it possible to have enum as a mapping key type

mappingsolidity

When trying to compile the following code in browser-solidity:

pragma solidity ^0.4.4;

contract TestContract {
    enum TestEnum { ONE, TWO, THREE }
    mapping (TestEnum => uint) testMapping;
}

I get the following error:

Untitled:5:14: Error: Expected elementary type name for mapping key type
    mapping (TestEnum => uint) testMapping;

Solidity documentation does not seem to forbid using enum as mapping key type, stating that "_KeyType can be almost any type except for a mapping":

https://solidity.readthedocs.io/en/develop/types.html?highlight=mapping#mappings

How can I implement a mapping with a custom enum as the key type?

Closely related:
Is it possible to have user-defined Struct as a _KeyType in a Mapping in Solidity?
Is it possible to have a mapping with a hash as key?

Best Answer

That feature is not currently implemented. A simple workaround is to do

pragma solidity ^0.4.4;

 contract TestContract {
    enum TestEnum { ONE, TWO, THREE }
    mapping (bytes32 => uint) testMapping;

    function getValueOne() constant returns(uint) {
        return testMapping[sha3(TestEnum.ONE)];
    }

}

Just use the hash of the enum for the key instead of the actual enum item, and it will work fine.

Related Topic