如何在Golang中找到来自控制台的标志数量

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

How to find number of flags coming from console in Golang

问题

我正在为你进行翻译,以下是翻译好的内容:

我正在从控制台传递参数。还有一些标志,例如:

go run test.go "-IP=10.10.10.10" "-db=kite" "-wv=45" "-cv=75" "A = value1" "B = value2" "C = 100" "D := ((A-B)/A)*C" "D ?"

在这里,-IP-db-wv-wc 这四个是标志,其他的作为普通参数传递,据我所知。

标志的数量可以是可变的。

我如何知道有多少个标志被传递给我的程序?在这种情况下,传递了4个标志。

英文:

I'm passing argument from console. There are some flags too. Like:

go run test.go "-IP=10.10.10.10" "-db=kite" "-wv=45" "-cv=75" "A = value1" "B = value2" "C = 100" "D := ((A-B)/A)*C" "D ?"

Here, -IP, -db, -wv, -wc these four are flags and others are passing as normal argument as I know.

Number of flags can be variable.

How can I know how many flags are passed to my program. In this case 4 flags are passed.

答案1

得分: 4

如果你使用标准的flag包来解析命令行标志,你可以调用NFlag函数来获取标志的数量:

package main
import "fmt"
import "flag"

func main() {
        flag.Bool("a", true, "A value")
        flag.Bool("b", true, "B value")
        flag.Parse()

        fmt.Println(flag.NFlag())
}

测试:

$ go run test.go 
0
$ go run test.go -a
1
$ go run test.go -a -b
2
英文:

If you use the standard flag package to parse command-line flags, you can call the NFlag function to get the number of flags:

package main
import "fmt"
import "flag"

func main() {
        flag.Bool("a", true, "A value");
        flag.Bool("b", true, "B value");
        flag.Parse();

        fmt.Println(flag.NFlag())
}

Test:

$ go run test.go 
0
$ go run test.go -a
1
$ go run test.go -a -b
2

huangapple
  • 本文由 发表于 2015年9月1日 19:37:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/32330631.html
匿名

发表评论

匿名网友

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

确定