Solidity结构体嵌套动态数组编译报错的解决方法咨询
解决Solidity中结构体数组从memory复制到storage的编译错误
问题场景
你定义了以下Solidity结构体:
struct ProductQuantity{ string product; //MUDAR PARA PRODUCT uint128 quantity; string unity; string originMachine; //MUDAR PARA MACHINE } struct Movement{ string originMachine; //mudar para MACHINE string destinationMachine; //mudar para MACHINE string responsibleWorker; //mudar para WORKER ou ids ProductQuantity[] product; }
尝试注册新Movement时编写了如下函数:
function registerMovement (string memory originMachine, string memory destinyMachine, string memory newWorker, ProductQuantity[] memory products) public { Movement memory newMovement = Movement({ originMachine: originMachine, destinationMachine: destinyMachine, responsibleWorker: newWorker, product: products }); movements.push(newMovement); }
编译时出现错误:
UnimplementedFeatureError: Copying of type struct ProductQuantity memory[] memory to storage not yet supported
使用Solidity 0.8.19版本在Remix IDE开发,需要保留数组结构。
解决方案
Solidity 0.8.x版本暂不支持直接将memory中的结构体数组复制到storage的结构体数组中,需要手动遍历数组逐个添加元素。修改后的函数如下:
// 假设合约中已定义storage数组:Movement[] public movements; function registerMovement (string memory originMachine, string memory destinyMachine, string memory newWorker, ProductQuantity[] memory products) public { // 先向storage数组添加空Movement,获取其storage引用 movements.push(); Movement storage newMovement = movements[movements.length - 1]; // 赋值基础字段 newMovement.originMachine = originMachine; newMovement.destinationMachine = destinyMachine; newMovement.responsibleWorker = newWorker; // 遍历传入的memory数组,逐个将元素添加到storage数组 for (uint256 i = 0; i < products.length; i++) { newMovement.product.push(products[i]); } }
原理说明
通过先创建storage类型的Movement实例,再手动遍历memory中的products数组,逐个将元素push到storage的product数组中,避开了Solidity暂不支持的直接数组复制操作,同时保留了原有的数组结构。
内容的提问来源于stack exchange,提问作者Miguel Macedo
相关产品推荐
相关产品推荐

