Solidity中如何填充包含动态数组的存储结构体?
Solidity中填充含动态数组的存储结构体的正确方式
你遇到的UnimplementedFeatureError是因为Solidity目前不支持直接将memory类型的动态数组赋值给storage类型的动态数组,需要手动逐个处理数组元素,而非直接整体赋值。
方法一:遍历内存数组,逐个添加到存储数组
修改构造函数,先初始化存储结构体的时间戳,再遍历内存中的Recipient数组,将每个元素逐个push到存储的recipients数组中:
struct Recipient { address target; uint256 amount; } struct Reward { uint256 timestamp; Recipient[] recipients; } contract Mwe { Reward reward; constructor() { // 先设置时间戳 reward.timestamp = block.timestamp; // 创建内存数组并初始化元素 Recipient[] memory recipients = new Recipient[](1); recipients[0] = Recipient(msg.sender, 1); // 遍历内存数组,逐个添加到存储数组 for (uint256 i = 0; i < recipients.length; i++) { reward.recipients.push(recipients[i]); } } }
方法二:直接操作存储数组,无需内存数组中转
如果不需要先在内存中构建数组,也可以直接操作存储的recipients数组,通过push或者扩容后赋值的方式添加元素:
struct Recipient { address target; uint256 amount; } struct Reward { uint256 timestamp; Recipient[] recipients; } contract Mwe { Reward reward; constructor() { reward.timestamp = block.timestamp; // 直接push元素到存储数组 reward.recipients.push(Recipient(msg.sender, 1)); // 或者先扩容再赋值(适合已知元素数量的场景) // reward.recipients.push(); // 扩容一个元素 // reward.recipients[0] = Recipient(msg.sender, 1); } }
原理说明
Solidity中storage和memory的动态数组底层存储机制不同:
memory数组是在执行期间分配的临时内存块,大小固定;storage数组则是存储在区块链上的动态结构,需要逐个元素写入。
因此无法直接进行整体拷贝,必须通过遍历逐个添加元素,或者直接操作存储数组完成初始化。
内容的提问来源于stack exchange,提问作者Fabien
相关产品推荐
相关产品推荐

