Solidity 中 uint 到 int 的转换错误
Conversion error from uint to int in Solidity
我一直在努力学习扎实。
写了一个简单的程序如下图
pragma solidity >=0.8.12 <0.9.0;
contract Test {
int[] staticArray = [int(1), int(2), int(3), int(4), int(5)];
function getStaticArray(int _pos) public view returns(int) {
int ret = staticArray[_pos];
return ret;
}
}
但由于某种原因给出以下转换错误:
TypeError: Type int256 is not implicitly convertible to expected type
uint256.
--> first.sol:13:31:
|
13 | int ret = staticArray[_pos];
| ^^^^
我不确定为什么会抛出这个错误。有人可以帮我吗?
在数组中使用索引时,必须使用 uint 而不是 int。
function getStaticArray(uint _pos) public view returns(int) {
int ret = staticArray[_pos];
return ret;
}
由于数组的索引必须是 non-negative,Solidity 编译器要求它是无符号的。
因此,您需要将 int _pos
更改为 uint _pos
。
请注意 uint
是 uint256
的别名,您通常可以使用任何其他无符号类型。
我一直在努力学习扎实。
写了一个简单的程序如下图
pragma solidity >=0.8.12 <0.9.0;
contract Test {
int[] staticArray = [int(1), int(2), int(3), int(4), int(5)];
function getStaticArray(int _pos) public view returns(int) {
int ret = staticArray[_pos];
return ret;
}
}
但由于某种原因给出以下转换错误:
TypeError: Type int256 is not implicitly convertible to expected type uint256.
--> first.sol:13:31:
|
13 | int ret = staticArray[_pos];
| ^^^^
我不确定为什么会抛出这个错误。有人可以帮我吗?
在数组中使用索引时,必须使用 uint 而不是 int。
function getStaticArray(uint _pos) public view returns(int) {
int ret = staticArray[_pos];
return ret;
}
由于数组的索引必须是 non-negative,Solidity 编译器要求它是无符号的。
因此,您需要将 int _pos
更改为 uint _pos
。
请注意 uint
是 uint256
的别名,您通常可以使用任何其他无符号类型。