如何在Go语言中访问带有连字符但没有值的命令行参数

huangapple go评论80阅读模式
英文:

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())
}

huangapple
  • 本文由 发表于 2017年1月11日 21:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/41592185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定