如何与映射的映射相互作用以实现结构?
我已经用嵌套映射创建了结构。考虑合同中写入的以下代码:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract TestContract {
struct Item {
uint itemId;
uint itemValue;
}
struct OverlayingItemStruct {
mapping(uint => Item) items;
uint overlayingId;
uint itemsCount;
}
mapping(uint => OverlayingItemStruct) public overlayingItems;
uint public overlayCount;
function addOverlayingItemsStruct(uint _value) external {
overlayCount ++;
mapping(uint => Item) memory items;
items[1] = Item(1, _value);
overlayingItems[overlayCount] = OverlayingItemStruct(items, 1, 1);
}
function addItem(uint _value, uint _overlayId) external {
OverlayingItemStruct storage overlay = overlayingItems[_overlayId];
overlay.itemsCount ++;
overlay.items[overlay.itemsCount] = Item(overlay.itemsCount, _value);
}
}
编译上述代码时,我会遇到错误:
TypeError: Uninitialized mapping. Mappings cannot be created dynamically, you have to assign them from a state variable.
--> TestC.sol:21:5:
|
21 | mapping(uint => Item) memory items;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
不确定,如何处理此错误。 其次,需要确认在嵌套映射字典中添加新值的方法是否正确?
I have created struct with nested mapping. Consider the following piece of code written inside the contract in solidity:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract TestContract {
struct Item {
uint itemId;
uint itemValue;
}
struct OverlayingItemStruct {
mapping(uint => Item) items;
uint overlayingId;
uint itemsCount;
}
mapping(uint => OverlayingItemStruct) public overlayingItems;
uint public overlayCount;
function addOverlayingItemsStruct(uint _value) external {
overlayCount ++;
mapping(uint => Item) memory items;
items[1] = Item(1, _value);
overlayingItems[overlayCount] = OverlayingItemStruct(items, 1, 1);
}
function addItem(uint _value, uint _overlayId) external {
OverlayingItemStruct storage overlay = overlayingItems[_overlayId];
overlay.itemsCount ++;
overlay.items[overlay.itemsCount] = Item(overlay.itemsCount, _value);
}
}
When compiling the above code, I am getting the error:
TypeError: Uninitialized mapping. Mappings cannot be created dynamically, you have to assign them from a state variable.
--> TestC.sol:21:5:
|
21 | mapping(uint => Item) memory items;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Not sure, how to handle this error.
Secondly, needed to confirm if the method to add new values in the nested mapping dictionary is correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在函数和
内存
状态中,不能在函数中声明映射。此类型仅具有存储
状态。这样说,要将映射传递到一个结构中,您可以将嵌套映射的钥匙设置为内部的相对结构。
我试图这样调整您的智能合约:
A mapping cannot be declare inside a function and in
memory
state. This type has onlystorage
state.Said this, to pass a mapping into a struct, you can set the key of nested mapping and pass relative struct inside it.
I tried to adjust your smart contract like this: