我需要在我的 go 代码中使用配置,我想从命令行加载配置路径。 我试试:
if len(os.Args) > 1 {
configpath := os.Args[1]
fmt.Println("1") // For debug
} else {
configpath := "/etc/buildozer/config"
fmt.Println("2")
}
然后我使用配置:
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 debugging purposes
} else {
configPath = "/etc/buildozer/config"
fmt.Println("2")
}
注意 if
中的“configPath =
”(而不是 :=
)。
这样 configPath
在 if
之前定义并且在 if
之后仍然可见。
在“Declarations and scope”/“Variable declarations”中查看更多信息。
关于command-line - 如何在 golang 中正确使用 os.Args?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193610/