How to initialize a mapping in Solidity, what is the best practice?

Viewed 2270

I would like to initialise my mapping in the declaration line in a smart contract. I was wondering what is the best practice? I have tried the following but Remix is giving me errors:

mapping(address _addr) public view myMap = [ addr-1 : true, addr-2 : false, addr-3 : true ];

2 Answers

You need to declare the variable first, and then assign it values on separate lines.

pragma solidity ^0.8;

contract MyContract {
    mapping(address => bool) public myMap;
    
    constructor() {
        myMap[address(0x123)] = true;
        myMap[address(0x456)] = false;
        myMap[address(0x789)] = true;
    }
}

Unfortunately, you can't. See the Solidity documentation for details on the reasons why. Your only option is to iterate through the keys.

If you don't know your set of keys ahead of time, you'll have to keep the keys in a separate array inside your contract.

Related