go install github.com/mrexox/gen-singleton-functions@latest
Add the following line in your source code
//go:generate gen-singleton-functions github.com/account/repo/package *MyType
If you want a value receiver then pass a type name without an asterisk
//go:generate gen-singleton-functions github.com/account/repo/package MyType
Make Dog
methods Bark
and Validate
public functions of a package dog
.
// dog/dog.go
package dog
import "fmt"
//go:generate gen-singleton-functions github.com/me/animals/dog *Dog
type Dog struct {
numTails int
barkingSound string
}
func (d *Dog) Bark() string {
return d.barkingSound
}
func (d *Dog) Validate() error {
if d.numTails != 1 {
return fmt.Errorf("unexpected number of tails: %d", d.numTails)
}
return nil
}
After running go generate ./...
the resulting file will contain the following:
// dog/dog_gen.go
//
// Code generated by generator, DO NOT EDIT.
//
// This file provides the wrappers for exported methods of a global var `globalDog`.
package dog
var globalDog *Dog
func SetGlobalDog(v *Dog) {
globalDog = v
}
// Bark calls `globalDog.Bark`.
func Bark() string {
if globalDog == nil {
panic("globalDog must be set before calling Bark()")
}
return globalDog.Bark()
}
// Validate calls `globalDog.Validate`.
func Validate() error {
if globalDog == nil {
panic("globalDog must be set before calling Validate()")
}
return globalDog.Validate()
}