command-line - 如何在 golang 中正确使用 os.Args?

标签 command-line go

我需要在我的 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 =”(而不是 :=)。

这样 configPathif 之前定义并且在 if 之后仍然可见。

在“Declarations and scope”/“Variable declarations”中查看更多信息。

关于command-line - 如何在 golang 中正确使用 os.Args?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193610/

相关文章:

xcode - 安装命令行工具 Xcode 5

batch-file - Windows : unable to control output video length and problems with using wildcards 上的 MLT 融化幻灯片

linux - 更改Linux中的符号链接(symbolic link)

go - 如何在被测函数内创建模拟

golang 全局变量访问在基准测试中很慢

regex - 重写正则表达式而不使用否定

linux - CURL 进度条 : How to pipe and extract numbers only using grep?

linux - 使用 util-linux 重命名命令

arrays - 使用 mgo.v2 将新对象插入到 mongodb 文档中的数组属性中

Go (golang) 中的 MongoDB 与 mgo : how to use logical operators to query?