Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to use string as a key in a mapping in Solidity aka. how to store short strings cheape
//
// In Solidity, a mapping is like a hashmap and works with `string` like this:
// mapping (string => uint) a;
//
// However it doesn't support accessors where string is a key:
// mapping (string => uint) public a;
//
// "Internal compiler error: Accessors for mapping with dynamically-sized keys not yet implemented."
//
// An accessor returns uint when called as `a(string)`.
//
// As a short term solution, until it is implemented in Solidity, use the conversion code below. It also uses half as much storage space.
//
// See more utilities soon at https://github.com/axic/density
//
library StringAsKey {
function convert(string key) returns (bytes32 ret) {
if (bytes(key).length > 32) {
throw;
}
assembly {
ret := mload(add(key, 32))
}
}
}
@amilano

This comment has been minimized.

amilano commented Aug 30, 2017

Thanks for this solution, but can you explain how is this applied? for what I understand this solution propose to declare the mapping like this(?): mapping (bytes32 => uint) public a;, is that right?

so to access the mapping one should do like this: a[convert("some_key")];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment