0

I try something like this:

mapping (uint256 =>string) public example;

then i initialze 'example' in the constructor

example[0]="apple";
example[1]="peach";

then i define a variable like this

string fruit=example[1];

However: "fruit" never receives any value while 'example' is successfully initialized. (deploying works fine - the compiler (remix) doesnt show any error. I checked the spelling of everything like 10x)

Please help me!

2 Answers 2

0

If you declare a local variable you should use memory, example with hardhat log:

import "hardhat/console.sol";

contract Foo {
    mapping (uint256 => string) public example;

    constructor () {
        example[0] = "apple";
        example[1] = "peach";
    }

    function foo () external {
        string memory fruit = example[1];
        console.log("Fruit is:", fruit);
    }
}
0

Its due to how solidity's compiler solves the instructions, fruit is a state variable so when you initialize it the value of example[1] is empty because the constructor gets called after the initialization of state variables. To solve this you can define the fruit as state variable and initialize it in the constructor, example:

mapping (uint256 =>string) public example;
    string fruit;

    constructor(){
        example[0]="apple";
        example[1]="peach";
        fruit = example[1];
    }

This way fruit is initialized correctly. Please accept and upvote if it helps

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.