Singleton in go

后端 未结 9 2022
心在旅途
心在旅途 2021-01-30 10:46

How does one implement the Singleton design pattern in the go programming language?

9条回答
  •  深忆病人
    2021-01-30 11:01

    The best approach will be:

     package singleton
    
     import "sync"
    
     type singleton struct {
     }
    
     var instance *singleton
     var once sync.Once
    
     func GetInstance() *singleton {
         once.Do(func() {
             instance = &singleton{}
         })
         return instance
     }
    

    You should read this Link

提交回复
热议问题