检查是否所有的标志都已设置(没有空白的标志)。

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

Check if all flags were set (no flags blank)

问题

如何确保每个标志参数都是从命令行设置的?我希望在不逐个检查每个标志名称的情况下实现这一点,并且希望动态地检查所有标志。

这是我的代码,main.go

package main

import (
	"fmt"
    "flag"
)

func main() {
	x := flag.String("x", "", "x标志")
	y := flag.String("y", "", "y标志")
    flag.Parse()
}

例如,我像这样运行它:go run main.go -x hello

英文:

How do I make sure every flag argument was set from the command line? I would like to do this without checking each flag name specifically, and would like to instead check all flags dynamically.

Here is my code, main.go:

package main

import (
	"fmt"
    "flag"
)

func main() {
	x := flag.String("x", "", "x flag")
	y := flag.String("y", "", "y flag")
    flag.Parse()
}

I run it, for example, like this: go run main.go -x hello

答案1

得分: 4

这可以通过使用VisitAll函数来实现。

VisitAll按字典顺序访问命令行标志,并为每个标志调用fn。它访问所有标志,即使那些未设置。

示例代码(在flag.Parse()之后添加):

flag.VisitAll(func (f *flag.Flag) {
    if f.Value.String()=="" {
        fmt.Println(f.Name, "未设置!")
    }
})
英文:

This can be achieved using the VisitAll function.

> VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

Sample code (add after flag.Parse()):

flag.VisitAll(func (f *flag.Flag) {
    if f.Value.String()=="" {
        fmt.Println(f.Name, "not set!")
    }
})

huangapple
  • 本文由 发表于 2017年7月18日 00:02:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/45148775.html
匿名

发表评论

匿名网友

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

确定