给定如下内容:
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不可隐式转换到期望的类型字符串内存[]内存
TypeError: Type string memory[3] memory不可隐式转换到期望的类型字符串内存[]内存
最优雅的方法是什么?是否应该初始化s
?您正在尝试将固定大小的数组["a","b"]
分配给动态大小的数组string[] s
。
对于s
的每个属性,需要事先预先确定动态大小数组的长度,然后逐一赋值。
pragma solidity ^0.8;
contract MyContract {
struct Strings {
string[] s;
}
function foo() external pure {
Strings[] memory strings = new Strings[](2);
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[1] = "c";
}
}