Solidity 0.5.0:TypeError 常量变量的初始值必须是编译时常量
Solidity 0.5.0: TypeError Initial value for constant variable has to be compile-time constant
为什么我不能在 Solidity 0.5.0 中以这种方式声明常量?使用最新版本一切正常:
uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals()));
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
在 Solidity 中,常量不会存储在任何地方;它们在字节码中被替换。大致是这样的:
constant uint256 FOO = 42;
function blah() {
return FOO;
}
变成这样:
function blah() {
return 42;
}
如果常量的值在编译时已知,则编译器只能执行此替换。在您的示例中,如果 _decimals
是一个常量,编译器理论上可以计算出 decimals()
returns 一个常量以及该值是多少,但 Solidity 编译器远非如此聪明
为什么我不能在 Solidity 0.5.0 中以这种方式声明常量?使用最新版本一切正常:
uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(decimals()));
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
在 Solidity 中,常量不会存储在任何地方;它们在字节码中被替换。大致是这样的:
constant uint256 FOO = 42;
function blah() {
return FOO;
}
变成这样:
function blah() {
return 42;
}
如果常量的值在编译时已知,则编译器只能执行此替换。在您的示例中,如果 _decimals
是一个常量,编译器理论上可以计算出 decimals()
returns 一个常量以及该值是多少,但 Solidity 编译器远非如此聪明