Solidity – Error When Using String Type as a Mapping Key

bytesmappingsoliditystring

The following code doesn't compile, because compiler needs a mapping key to be of fixed-size type in order to create accessor for a public mapping. I'm using here string type. My strings are 24 byte hex strings.

My question:

  • How would you cast string to any fixed-size type that can be used
    as a mapping key?

  • Do you have any advice on how to make the code more effiecent?


pragma solidity ^0.4.6;
contract C {
    struct User {
         uint balance;
    }
    mapping (string => User) public accounts;
    function newUser(string id, uint balance) {
         accounts[id] = User(balance);
    }
}

Error: Unimplemented feature: Accessors for mapping with dynamically-sized keys not yet implemented.

Best Answer

I am proposing using bytesN instead string:

pragma solidity ^0.4.6;
contract C {
    struct User {
         uint balance;
    }
    mapping (bytes24 => User) public accounts;
    function newUser(bytes24 id, uint balance) {
         accounts[id] = User(balance);
    }
}

you could also convert bytes to string look at : How to convert a bytes32 to string

Related Topic