我有兩個固定長度的陣列,我想將它們發送到一個實用程式函式,但是由于陣列長度不同,它給出了以下錯誤。
TypeError: Invalid type for argument in function call. Invalid implicit conversion from string storage ref[2] storage ref to string storage ref[] storage pointer requested.
有沒有辦法制作一個效用函式,它可以采用任意長度的固定陣列?
完整的代碼片段
contract test {
string[2] internal list1 = ["str1", "str2"];
string[3] internal list2 = ["str3", "str4", "str5"];
function entryPoint() public view returns (uint256) {
return utilityFunction(list1, list2);
}
function utilityFunction(string[] storage _list1, string[] storage _list2) internal pure returns (uint256 result) {
// some logic here
}
}
uj5u.com熱心網友回復:
您可以讓函式接受預定義的固定長度
// changed `string[]` to `string[2]` and the other `string[]` to `string[3]`
function utilityFunction(string[2] storage _list1, string[3] storage _list2) internal pure returns (uint256 result) {
或者您可以首先將陣列轉換為動態大小,然后將它們傳遞給動態大小接受函式
function entryPoint() public view returns (uint256) {
// declare a dynamic-size array in memory with 2 empty items
string[] memory _list1 = new string[](2);
// assign values to the dynamic-size array
_list1[0] = list1[0];
_list1[1] = list1[1];
string[] memory _list2 = new string[](3);
_list2[0] = list2[0];
_list2[1] = list2[1];
_list2[2] = list2[2];
// pass the dynamic-size in-memory arrays
return utilityFunction(_list1, _list2);
}
// changed location to memory, now you can accept dynamic-size arrays with arbitrary length
function utilityFunction(string[] memory _list1, string[] memory _list2) internal pure returns (uint256 result) {
}
但是目前 (v0.8) 無法接受任意長度的固定大小陣列。只需使用預定義的長度。
注:有一個在我一些空間,為優化氣entryPoint()例如(通過在記憶體中的副本list1,并list2在第一,然后分配時,從記憶體中拷貝讀取_list1和_list2值)。但我的目標是制作一個更清晰的示例來分配動態大小的陣列,而不是通過優化來降低代碼的可讀性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367588.html
上一篇:如何將帶有陣列的物件轉換為陣列
下一篇:操作陣列元素
