命令行 – 如何正确使用golang中的os.Args?

我需要在我的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”.

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...