Singleton
A singleton is a value of which there is one in the process. In Go that is usually a package-level variable initialized with sync.Once or init, not a class with a private constructor.
Detailed Explanation
Java singletons fight the language's constructors. Go has package scope. var defaultClient = newClient() or var client *Client; var once sync.Once plus func Default() *Client { once.Do(...); return client } is the pattern. There is no class, no private Singleton(), no inheritance.
Prefer injection. A singleton default is convenient and painful in tests: two tests share mutable state, order depends on init. Pass *Client into NewServer. Offer Default() only for small programs and for compatibility.
init vs Once. init runs at load, cannot return an error, and runs in tests that import the package. Once runs on first use and can pair with OnceValues for (T, error). Use Once for anything that can fail or that tests should skip.
Mutable singletons are shared state. A package-level map or *sql.DB used from many goroutines must be safe (the DB pool is; your map is not). Document if Default() is safe for concurrent use.
What it costs. Hidden coupling. A process-wide client is hard to give two configs. The Go way is a value you construct, plus an optional package-level helper for the default.
Code Examples
package client
import "sync"
type Client struct{ addr string }
var (
once sync.Once
c *Client
)
func Default() *Client {
once.Do(func() {
c = &Client{addr: "localhost:8080"}
})
return c
}
func New(addr string) *Client {
return &Client{addr: addr}
}type Server struct{ c *Client }
func NewServer(c *Client) *Server {
if c == nil {
c = Default()
}
return &Server{c: c}
}Common Gotchas
Package-level mutable state races and wrecks tests
inject, or lock, or do not mutate.
`sync.Once` is the concurrency-safe constructor
a plain `var x = New()` is also a singleton, initialized before `main`.
There is no private constructor
unexported `type client struct` plus exported `Default()` is the visibility tool.
`init` that dials the network makes `go test` slow and flaky
`init` that dials the network makes `go test` slow and flaky