3

f.e in Python:

mappingName = {
  'key1': 'value1', 
  'key2': 'value2'
}

What are the best practices to achieve that?

3
  • Why don't you simply try and see what the compiler tells you? May 8 '19 at 10:06
  • ParserError: Expected primary expression. mapping(uint256 => bytes32) public currencyByNumber = {3: 'value'}; May 8 '19 at 10:09
  • 1
    Well, in that case I'd say that you can't. May 8 '19 at 10:11
4

Sure, you may do this in constructor:

mapping (string => string) myMapping;

constructor () public {
  myMapping ["key1"] = "value1";
  myMapping ["key2"] = "value2";
}
5
  • 1
    While this answers the question in the title, it seems that the actual intention of the person who asked it is to know whether the initialization can be done at the declaration line (to which the answer is no, as far as I know). Moreover, the question in the title is technically meaningless, because every variable in this language (and in any other language that I'm aware of) can be initialize with a predefined value. Think about it - the language would be useless otherwise! May 8 '19 at 10:28
  • 1
    OP didn't say anything about declaration line, but just showed a Python code and asked how to achieve similar behavior in Solidity. I don't think author meant that syntax should be in any way similar as well, because it is quite odd to expect similar syntax from languages as different from each other as Python is different from Solidity. May 8 '19 at 10:34
  • Even so, a link to solidity official documentation (as a comment to the question), would probably be more appropriate. The question itself should probably be closed (there would be millions of redundant such questions otherwise). And again, I'm pretty sure that if this dude knows the keyword mapping, then he also knows the basic initialization syntax. It makes sense that he's looking for a "non-basic" syntax. May 8 '19 at 10:36
  • I was asked to know if it is possible in declaration level and in case it's not possible, is there a best practice to do it - Constructor, function that will be called from the constructor, library? May 8 '19 at 10:46
  • 1
    Constructor is probably the best place, because it is guaranteed to be executed only once. Also, in case your initial values may be calculated from corresponding keys, you may consider lazy initialization. May 8 '19 at 10:47

Your Answer

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

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