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