命令行 – 如何正确使用golang中的os.Args?
发布时间:2020-12-16 19:03:22 所属栏目:大数据 来源:网络整理
导读:我需要在我的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 :
我需要在我的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”. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |