我需要在我的go代码中使用config,我想从命令行加载配置路径.
我尝试:
if len(os.Args) > 1 {
configpath := os.Args[1]
fmt.Println("1") // For debug
} else {
configpath := "/etc/buildozer/config"
fmt.Println("2")
}
然后我用config:
configuration := config.ConfigParser(configpath)
当我使用参数(或没有)启动我的go文件时,我收到类似的错误
# command-line-arguments src/2rl/buildozer/buildozer.go:21: undefined: configpath
我该如何正确使用os.Args?
在if的范围之外定义configPath.configPath := ""
if len(os.Args) > 1 {
configpath = os.Args[1]
fmt.Println("1") // For debug
} else {
configpath = "/etc/buildozer/config"
fmt.Println("2")
}
注意if中的’configPath ='(而不是:=).
这样就可以在之前定义configPath,并且在if之后仍然可见.
更多信息请参见“Declarations and scope”/“Variable declarations”.