在Solidity中,你可以在函数内部声明映射变量吗?

问题描述 投票:0回答:2

我只看到映射变量被声明为存储变量。 我想知道是否可以在 Solidity 中的函数内部声明映射变量。

mapping storage ethereum blockchain solidity
2个回答
4
投票

不,这是不可能的,因为映射不能动态创建,您必须从状态变量分配它们。然而,您可以创建对映射的引用,并为其分配存储变量。

但是,您可以将映射封装在合约中,并通过实例化包含该映射的新合约来在另一个合约中使用它,这是在函数内“声明”映射的最近似方法。

// 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));
    }
}

取自文档


3
投票

solidity 中的映射始终存储在存储中并声明为顶级,如文档所述。

但是,如果它引用函数内的顶级映射,则在函数内声明映射。

// 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;
}

}

尽管我不确定用例是什么,但引用

addToMappingInsideFunction
内部的顶级映射是有效的语法。

© www.soinside.com 2019 - 2024. All rights reserved.