初始化const变量 [英] Initialize const variable
问题描述
如何使用 const
类型初始化 KILO
变量?
How can I initialize KILO
variable with const
type?
const KILO = math.Pow10(3)
因为我有错误
const initializer math.Pow10(3) is not a constant
推荐答案
常量声明不能包含函数调用(某些例外,请参阅下文),必须对其进行求值
Constant declarations cannot contain function calls (with some exceptions, see below), they must be evaluated at compile time while a function call is carried out at runtime.
常量值由符文, integer ,浮点,虚构,或字符串文字,表示标识符常量,常量表达式,转换,其结果是一个常量,或者是某些内置函数的结果值,例如
unsafe.Sizeof
应用于任何值,上限
或len
应用于某些表达式,real
和imag
A constant value is represented by a rune, integer, floating-point, imaginary, or string literal, an identifier denoting a constant, a constant expression, a conversion with a result that is a constant, or the result value of some built-in functions such as
unsafe.Sizeof
applied to any value,cap
orlen
applied to some expressions,real
andimag
applied to acomplex
constant and complex applied to numeric constants.
并引用到 complex
常量,将复数应用于数字常量。来自规范:常量表达式:
And quoting from Spec: Constant expressions:
常量表达式只能包含常量操作数,并在编译时求值。
请注意,有一些内置函数可以在常量声明中调用,例如 unsafe.Sizeof()
,
Note that there is a small set of (builtin) functions that may be called in constant declarations such as unsafe.Sizeof()
, but generally you can't do that.
所以只需使用
const Kilo = 1000 // Integer literal
Or
const Kilo = 1e3 // Floating-point literal
有关Go常量的广泛介绍,请阅读博客文章:常量
For an extensive introduction to Go constants, read blog post: Constants
如果由于某种原因您确实需要调用函数,则无法将其存储在常量中,它必须是变量,例如:
If for some reason you do need to call a function, you cannot store it in a constant, it must be a variable, e.g.:
var Kilo = math.Pow10(3)
另请参阅相关的紧凑地将10的幂作为常数写。
这篇关于初始化const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!