如何正确使用golang中的os.Args?

Dmi*_*dov 6 command-line go

我需要在我的go代码中使用config,我想从命令行加载配置路径.我尝试:

if len(os.Args) > 1 { 
        configpath := os.Args[1]
        fmt.Println("1") // For debug
    } else {
        configpath := "/etc/buildozer/config"
        fmt.Println("2")
    }
Run Code Online (Sandbox Code Playgroud)

然后我用config:

configuration := config.ConfigParser(configpath)
Run Code Online (Sandbox Code Playgroud)

当我使用参数(或没有)启动我的go文件时,我收到类似的错误

# command-line-arguments
src/2rl/buildozer/buildozer.go:21: undefined: configpath
Run Code Online (Sandbox Code Playgroud)

我该如何正确使用os.Args?

Von*_*onC 11

定义configPath在您的范围之外if.

configPath := ""

if len(os.Args) > 1 { 
  configpath = os.Args[1] 
  fmt.Println("1") // For debug 
} else { 
  configpath = "/etc/buildozer/config"
  fmt.Println("2") 
}
Run Code Online (Sandbox Code Playgroud)

注意里面的' configPath ='(而不是:=)if.

这种方式configPath在之前定义,并且在之后仍然可见if.

有关详细信息,请参阅" 声明和范围 "/" 变量声明 ".