英文:
How to access command line arguments with hyphens but without value in Go Lang
问题
我想要访问带有连字符的命令行参数,例如:
go run user.go -version
或者
go run user.go --version
当我执行这样的命令时,我收到以下错误信息:
flag provided but not defined: -version
Usage of /tmp/go-build354377460/command-line-arguments/_obj/exe/user:
--version string
prints current version and exits
exit status 2
以下是我的代码:
package main
import (
"flag"
"fmt"
)
func main() {
var version string
flag.StringVar(&version, "-version", "", "prints current version and exits")
// 解析命令行参数
flag.Parse()
fmt.Println(flag.Args())
}
非常感谢您的帮助。提前致谢。
英文:
I want to access command line arguments with hyphens for example:
go run user.go -version
or
go run user.go --version
When I executing like this, I received the below error:
flag provided but not defined: -version
Usage of /tmp/go-build354377460/command-line-arguments/_obj/exe/user:
--version string
prints current version and exits
exit status 2
Here is my code:
package main
import (
"flag"
"fmt"
)
func main() {
var version string
flag.StringVar(&version, "-version", "", "prints current version and exits")
// Parse the flags
flag.Parse()
fmt.Println(flag.Args())
}
Any help is greatly appreciated. Thanks in advance.
答案1
得分: 3
使用布尔类型。在标志定义中不要包含“-”。
func main() {
var version bool
flag.BoolVar(&version, "version", false, "打印当前版本并退出")
flag.Parse()
if version {
fmt.Println("hello")
return
}
fmt.Println(flag.Args())
}
英文:
Use a bool. Do not include the "-" in the flag definition.
func main() {
var version bool
flag.BoolVar(&version, "version", false, "prints current version and exits")
flag.Parse()
if version {
fmt.Println("hello")
return
}
fmt.Println(flag.Args())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论