Search code examples
goconstants

Initialize const variable


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

Solution

  • 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 or len applied to some expressions, real and imag applied to a complex 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.