无论如何要类型转换 solidity 数组中的所有元素?
Anyway to type convert all elements in solidity array?
我最近一直在尝试 Solidity。
在尝试创建 public int 数组时。
Test.sol
pragma solidity >=0.8.12 <0.9.0;
contract Test {
int[5] public array = [1, 2, 3, 4, 5];
}
抛出以下错误:
TypeError: Type uint8[5] memory is not implicitly convertible to
expected type int256[5] storage ref.
--> first.sol:4:27:
|
4 | int[5] public array = [1, 2, 3, 4, 5];
| ^^^^^^^^^^^^^^^
所以我尝试了类型转换,如下所示:
pragma solidity >=0.8.12 <0.9.0;
contract Test {
int[5] public array = [int(1), int(2), int(3), int(4), int(5)];
}
这行得通,但是对每个元素进行类型转换对我来说似乎并不传统。
还有其他办法吗?
--------------------编辑-------------------- ------
在 solidity 中,只需类型转换第一个元素即可。
所以下面解决了问题:
int[5] staticArray = [int(1), 2, 3, 4, 5];
这似乎是编译器中的错误。
足够小的数字文字(例如您示例中的 1 或 2)适合 uint8
的类型(最大值 255),因此编译器将文字视为 uint8
类型默认。
您需要使用 typecast 函数解决此问题,就像您的问题中所示。
int[5] public array = [int(1), int(2), int(3), int(4), int(5)];
希望它在以后的 Solidity 版本中得到修复。
我最近一直在尝试 Solidity。 在尝试创建 public int 数组时。
Test.sol
pragma solidity >=0.8.12 <0.9.0;
contract Test {
int[5] public array = [1, 2, 3, 4, 5];
}
抛出以下错误:
TypeError: Type uint8[5] memory is not implicitly convertible to expected type int256[5] storage ref.
--> first.sol:4:27:
|
4 | int[5] public array = [1, 2, 3, 4, 5];
| ^^^^^^^^^^^^^^^
所以我尝试了类型转换,如下所示:
pragma solidity >=0.8.12 <0.9.0;
contract Test {
int[5] public array = [int(1), int(2), int(3), int(4), int(5)];
}
这行得通,但是对每个元素进行类型转换对我来说似乎并不传统。 还有其他办法吗?
--------------------编辑-------------------- ------
在 solidity 中,只需类型转换第一个元素即可。 所以下面解决了问题:
int[5] staticArray = [int(1), 2, 3, 4, 5];
这似乎是编译器中的错误。
足够小的数字文字(例如您示例中的 1 或 2)适合 uint8
的类型(最大值 255),因此编译器将文字视为 uint8
类型默认。
您需要使用 typecast 函数解决此问题,就像您的问题中所示。
int[5] public array = [int(1), int(2), int(3), int(4), int(5)];
希望它在以后的 Solidity 版本中得到修复。