11

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.

2
  • 3
    You can't really cast a string to a fixed type. It looks like the issue is just with the accessor, though, not the mapping itself, so if you don't make the mapping public, and write the accessor yourself it may work Commented Dec 13, 2016 at 21:27
  • 2
    This is actually a somewhat complicated issue. Basically, in general, you can't return a custom type like User in a public function. Solidity has a nice little feature where you can return a custom struct from a public mapping, but only through a local call, not through an actual EVM operation. Dynamic keys mess with that Commented Dec 13, 2016 at 21:35

1 Answer 1

6

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

1
  • 2
    bytes is very different from the the "bytesN" type which include bytes24, bytes32.
    – eth
    Commented Jan 21, 2017 at 1:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.