一般写法
type singleton struct{ } var mu sync.Mutex var instance *singleton func GetInstance() *singleton{ if instance == nil{ mu.Lock() defer mu.Unlock() if instance == nil{ instance = &singleton{} } } return instance }
go 中更好的写法
type singleton struct { } var instance *singleton var once sync.Once func GetInstance() *singleton{ once.Do(func(){ instance = &singleton{} }) return instance }