In Solidity, can you declare a mapping variable inside function?
Asked Answered
E

2

5

I have only seen that the mapping variables are declared as storage variables. I'd like to know if I can declare a mapping variable inside the function in Solidity.

Eleen answered 9/6, 2022 at 23:12 Comment(0)
S
4

No, its not possible because mappings cannot be created dynamically, you have to assign them from a state variable. Yet you can create a reference to a mapping, and assign a storage variable to it.

Yet, you can encapsulate the mapping in a contract, and use it in another by instantiating a new contract containing that mapping, this is the most approximated way of "declaring" a mapping inside a function.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.4.0 <0.9.0;

contract MappingExample {
    mapping(address => uint) public balances;

    function update(uint newBalance) public {
        balances[msg.sender] = newBalance;
    }
}

contract MappingUser {
    function f() public returns (uint) {
        MappingExample m = new MappingExample();
        m.update(100);
        return m.balances(address(this));
    }
}

Taken form the docs:

enter image description here

Strung answered 10/6, 2022 at 0:2 Comment(0)
W
3

Mappings in solidity are always stored in the storage and declared top-level as docs say.

But you declare a mapping inside a function if it refers to a top-level mapping inside a function.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract MappingInFunction {
    mapping (uint => string) public Names;
    uint public counter;
   
    function addToMappingInsideFunction(string memory name) public returns (string memory localName)  {
        mapping (uint => string) storage localNames = Names;
        counter+=1;
        localNames[counter] = name;
        return localNames[counter];

        // we cannot return mapping in solidity
        // return localNames;
}

}

Even though I am not sure what would be the use case but referring to top-level mapping inside addToMappingInsideFunction is a valid syntax.

Wilful answered 18/8, 2022 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.