【发布时间】:2022-08-19 06:30:56
【问题描述】:
我只看到映射变量被声明为存储变量。 我想知道我是否可以在 Solidity 的函数中声明一个映射变量。
标签: function mapping storage ethereum solidity
我只看到映射变量被声明为存储变量。 我想知道我是否可以在 Solidity 的函数中声明一个映射变量。
标签: function mapping storage ethereum solidity
不,这是不可能的,因为映射不能动态创建,您必须从状态变量中分配它们。然而,您可以创建对映射的引用,并为其分配存储变量。
然而,您可以将映射封装在合约中,并通过实例化包含该映射的新合约在另一个合约中使用它,这是在函数内“声明”映射的最近似方式。
// 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));
}
}
取自docs:
【讨论】:
正如文档所说,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 中引用顶级映射是一种有效的语法。
【讨论】: