Reputation: 3029
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?
Upvotes: 19
Views: 51323
Reputation: 31701
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")
}
}
Upvotes: 22