How can I initialize KILO
variable with const
type?
const KILO = math.Pow10(3)
Because I have an errror
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.
Quoting from Spec: Constants:
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.
And quoting from Spec: Constant expressions:
Constant expressions may contain only constant operands and are evaluated at compile time.
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.
So just use
const Kilo = 1000 // Integer literal
Or
const Kilo = 1e3 // Floating-point literal
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)
Also see related Writing powers of 10 as constants compactly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With