Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ];

like image 426
johnDoe Avatar asked Nov 02 '25 09:11

johnDoe


1 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;
    }
}
like image 151
Petr Hejda Avatar answered Nov 04 '25 04:11

Petr Hejda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!