我想知道为什么如果我的函数要返回一个不确定长度的字符串,为什么不能返回一个一定长度的字符串数组。
例如,这个函数不编译
function BindingTypeList() public pure returns(string[] memory) {
return ["DocumentTemplate", "Definition", "RepAndWarranty", "Restriction", "Entitlement"];
}错误消息是TypeError: Return argument type string memory[5] memory is not implicitly convertible to expected type (type of first return variable) string memory[] memory.
他们似乎在说string[5]与returns(string[])不兼容。我一点也不明白。有解决办法吗?
发布于 2021-09-03 12:08:37
您正在尝试返回一个动态数组(string[]),但实际上,return语句实例化了一个固定数组(string[5])。
快速修复:返回string[5] memory (而不是string[] memory)。
Solidity (v0.8)目前无法调整内存中数组的大小。因此,您不能只在内存中定义一个空的动态数组,然后将push()放入其中。但是有一个方法可以返回一个动态数组,该数组包含预定义的项列表:
可以定义一个包含5个空项的动态数组,然后重新分配它们的值。
function BindingTypeList() public pure returns(string[] memory) {
string[] memory arr = new string[](5); // 5 empty items
arr[0] = "DocumentTemplate";
arr[1] = "Definition";
arr[2] = "RepAndWarranty";
arr[3] = "Restriction";
arr[4] = "Entitlement";
return arr;
}https://stackoverflow.com/questions/69038767
复制相似问题