Solidity中为变量赋值不同长度数组字面量的报错解决
Solidity动态数组赋值类型错误的优雅解决方法
定义的结构体及数组
struct Strings { string[] s; } Strings[] memory strings = new Strings[](2);
尝试执行的赋值操作
strings[0].s = ["a","b"]; strings[1].s = ["a","b","c"];
触发的类型错误
TypeError: Type string memory[2] memory is not implicitly convertible to expected type string memory[] memory
TypeError: Type string memory[3] memory is not implicitly convertible to expected type string memory[] memory
解决方法
问题根源是:["a","b"]这类写法创建的是固定长度的memory数组(比如string memory[2]),而结构体中定义的s是动态长度的string[]数组,Solidity不支持这两种类型的隐式转换。
最优雅的解决方式有两种:
显式创建动态数组并赋值元素
先初始化对应长度的动态数组,再逐个填充元素:// 处理第一个元素 strings[0].s = new string[](2); strings[0].s[0] = "a"; strings[0].s[1] = "b"; // 处理第二个元素 strings[1].s = new string[](3); strings[1].s[0] = "a"; strings[1].s[1] = "b"; strings[1].s[2] = "c";通过ABI编码解码完成类型转换
利用ABI的编码解码能力,将固定长度数组字面量转换为动态数组:strings[0].s = abi.decode(abi.encode(["a","b"]), (string[])); strings[1].s = abi.decode(abi.encode(["a","b","c"]), (string[]));
关于初始化的说明
不需要提前初始化结构体中的s成员,在赋值时直接为其创建动态数组并填充内容即可。
内容的提问来源于stack exchange,提问作者Newy
相关产品推荐
相关产品推荐

