1

I'm confused about mappings. I always used them by populating them through functions. Now I need a simple mapping with a handful of items and wanted to populate it like this:

mapping(uint8 => string) public myMap;
myMap[0] = "String A";
myMap[1] = "String B";

But I get a compiling error:

ParserError: Expected identifier but got '='

What am I doing wrong?

I tried to declare the mapping before the construct, and then populate it inside the construct, but then I'm not able to retrieve those 2 values later on in the contract. They look empty. I'm missing something :/

I'm using Solidity 0.8.22

1 Answer 1

2

You can only populate a mapping or an array in a function or in a construct, other variations not supported by Solidity.

Hence the error that you're getting: ParserError: Expected identifier but got '='

Re

I tried to declare the mapping before the construct, and then populate it inside the construct, but then I'm not able to retrieve those 2 values later on in the contract. They look empty. I'm missing something?

Here's a working PoC piece of code demonstrating how to populate a mapping inside a constructor and then retrieve these values later in a function:

    // SPDX-License-Identifier:
    pragma solidity 0.8.22;
    
    contract Test {
        mapping(uint8 => string) public myMap;
    
        address private immutable owner;
    
        constructor() {
            owner = msg.sender;
    
            myMap[0] = "String A";
            myMap[1] = "String B";
        }
    
        function retrieve(uint8 index) external view returns (string memory item) {
            item = myMap[index];
        }
    }

result

2
  • 1
    Thanks for the feedback Mila! I was doing good with the construct, I did like you wrote... but I was returning the wrong thing in the function retrieving the strings. Glad you insisted on that route!
    – user130657
    Feb 5 at 15:29
  • Glad it helped! You can test it to see if you're still getting unexpected strings. If there's still a problem, then the culprit might be how you access the mapping's values.
    – Mila A
    Feb 5 at 15:38

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.