Runtime Const in Golang

Constants in go are set at compile time, see the relevant section in the docs here: https://golang.org/doc/effective_go.html#constants

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.


As stated, there are no constructs supporting runtime constants in Go backed by the language spec or the Go runtime.

You can simpulate runtime constants though with unexported fields and with a "getter" method, e.g.:

package wrapper

type Immutable struct {
    value int
}

func (i Immutable) Get() int { // You may choose between pointer or value receiver
    return i.value
}

func New(value int) Immutable {
    return Immutable{value}
}

You can create values of Immutable with the New() constructor-like function, and no one* outside of package wrapper will be able to modify the wrapped int value (Immutable.value).

(*Note: no one means no one who is not touching package unsafe, but that doesn't count. Even in Java you can change values of final attributes using Java reflection.)

Tags:

Constants

Go