duanlongling5308
2016-07-29 11:00
采纳率: 0%
浏览 1.0k

在golang中仅设置一次全局变量

我有一个main.go文件:

// running the router in port 9000
func main() {
    router := routers.InitApp()
    router.RunTLS(":9000" , "domain.crt" , "domain.key")
}

在另一个文件里:

package utils
var ConfigMap = GetAppConfig
func GetAppConfig() map[string]string{
 ....//
}

ConfigMap是一个全局变量,每当我尝试访问utils.ConfigMap映射时,都会调用GetAppConfig函数。在GO项目中,如何在不初始化应用程序的情况下,调用此函数访问ConfigMap?

图片转代码服务由CSDN问答提供 功能建议

我有一个main.go文件,其中包含:

   //在端口9000中运行路由器
func main(){
 router:= routers.InitApp()
 router.RunTLS(“:9000”,“ domain.crt”,“ domain.key”)
}  
   
 
 

在另一个gofile中,我有

 包utils 
var ConfigMap = GetAppConfig 
func GetAppConfig()映射[ 字符串] string {
 .... // 
} 
   
 
 

ConfigMap是全局变量,每次我尝试访问 utils.ConfigMap < / code>映射 GetAppConfig 函数。 在应用程序初始化时,我如何才能只调用一次此函数,然后在go项目中我想要的任何位置访问ConfigMap。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dta25920 2016-07-29 11:03

    This is what package init() functions are for. They are executed once, before your package can be reached "from the outside":

    var ConfigMap map[string]string
    
    func init() {
        // Init ConfigMap here
    }
    

    Note that such exported global variables should be protected if you want to allow concurrent use. It would be unfeasible to leave this to the users of the package.

    For this purpose, you should declare ConfigMap unexported:

    var configMap[string]string
    

    And provide a getter function which would properly protect it with a Mutex:

    var confMux = &sync.Mutex{}
    
    func Config(name string) string {
        confMux.Lock()
        defer confMux.Unlock()
        return configMap[name]
    }
    
    打赏 评论
  • drox90250557 2016-07-30 02:11

    I believe there is a typo in the code that you posted. You define the configMap outside the init function like this:

    var configMap map[string]string
    

    This is fine but inside the init you also have this:

    var configMap = map[string]string{}
    

    Here you are shadowing the configMap that you have outside the init function meaning that you have declared the variable again inside the init. As a result when you access the variable outside of the init function you will get the global variable which is still empty. If you remove the var inside the init it would work fine.

    configMap = map[string]string{}
    

    Here's a quick demonstration.

    There is another typo in the original question:

    var configMap = GetAppConfig
    

    This should be:

    var configMap = GetAppConfig()
    

    You are assigning the function to a variable rather than result of the function.

    打赏 评论

相关推荐 更多相似问题