Search code examples
govariablesconstants

How to declare a constant from a variable?


What is the problem:

I would like to declare a constant from a variable. Here is a very simple version of what I'd like to do:

Go playground

someVar := 1
const someConst = someVar // error: const initializer someVar is not a constant
fmt.Printf("%d %d", someVar, someConst)

How can I make someConst a constant? Is this impossible in go?

Why do I want this?

someVar is a global Variable. It is fine that this can change. someConst is function scoped. For the scope of this function it should not change.

In DB terms: someConst is an immutable snapshot of someVar


Solution

  • You can't. Go's constants must be compile-time constants.

    A constant declaration binds a list of identifiers (the names of the constants) to the values of a list of constant expressions.

    And

    Constant expressions may contain only constant operands and are evaluated at compile time.

    someVar in your example is a variable, it does not qualify for the "constant operands".

    If the package level variable may change during the execution of your function which change you don't want to observe, make a local copy of the variable, and use the local copy.

    Also note that if the variable's value may change due to a (concurrent) goroutine, access to it (when making the copy) must be synchronized (just like the write to it in other goroutines).

    For example:

    var (
        someVarMu sync.RWMutex
        someVar   = 1
    )
    
    func foo() {
        someVarMu.RLock()
        myVar := someVar
        someVarMu.RUnlock()
    
        // Use myVar
        fmt.Println(myVar)
    }