Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a global constant accessible in all packages in golang?

Tags:

go

I have a constant defined within a package in golang as such:

package services

const (
   Source = "local"
)

I would like to make this constant accessible by other packages without having to import the package into my other module. How can I go about that?

like image 222
Ralph Avatar asked Apr 12 '18 06:04

Ralph


People also ask

How do you declare a constant in Golang?

To declare a constant and give it a name, the const keyword is used. Constants cannot be declared using the := syntax.

How do you declare a global constant?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

How do you use constants in Go?

In Go, const is a keyword introducing a name for a scalar value such as 2 or 3.14159 or "scrumptious" . Such values, named or otherwise, are called constants in Go. Constants can also be created by expressions built from constants, such as 2+3 or 2+3i or math. Pi/2 or ("go"+"pher") .


1 Answers

You cannot refer to services.Source without importing services.

However, you can avoid the dependency by creating a new constant in another package that happens to have the same value, and verify that with a test. That is, your test imports services, but your production code does not. The stdlib does this here and there to avoid a few dependencies.

// services.go
package services

const Source = "local"

// foo.go
package foo

const Source = "local"

// foo_test.go
package foo

import (
    "services"
    "testing"
)

func TestSource(t *testing.T) {
    if Source != services.Source {
        t.Error("Source != services.Source")
    }
}
like image 195
Peter Avatar answered Oct 12 '22 09:10

Peter