英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论