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?
To declare a constant and give it a name, the const keyword is used. Constants cannot be declared using the := syntax.
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.
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") .
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")
}
}
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