英文:
Flag command line parsing in golang
问题
我不确定我理解这个例子的推理(取自这里),也不知道它试图传达关于Go语言的什么信息:
package main
import (
"flag"
"fmt"
)
func main() {
f := flag.NewFlagSet("flag", flag.ExitOnError)
f.Bool("bool", false, "this is bool flag")
f.Int("int", 0, "this is int flag")
visitor := func(a *flag.Flag) {
fmt.Println(">", a.Name, "value=", a.Value)
}
fmt.Println("Visit()")
f.Visit(visitor)
fmt.Println("VisitAll()")
f.VisitAll(visitor)
// set flags
f.Parse([]string{"-bool", "-int", "100"})
fmt.Println("Visit() after Parse()")
f.Visit(visitor)
fmt.Println("VisitAll() after Parse()")
f.VisitAll(visitor)
}
在他们的设置基础上添加一个类似于下面的内容:
int_val := f.Get("int")
以获取命名参数似乎更有用。我对Go完全不熟悉,所以只是试图熟悉这门语言。
英文:
I'm not sure I understand the reasoning behind this example (taken from here), nor what it is trying to communicate about the Go language:
package main
import (
"flag"
"fmt"
)
func main() {
f := flag.NewFlagSet("flag", flag.ExitOnError)
f.Bool("bool", false, "this is bool flag")
f.Int("int", 0, "this is int flag")
visitor := func(a *flag.Flag) {
fmt.Println(">", a.Name, "value=", a.Value)
}
fmt.Println("Visit()")
f.Visit(visitor)
fmt.Println("VisitAll()")
f.VisitAll(visitor)
// set flags
f.Parse([]string{"-bool", "-int", "100"})
fmt.Println("Visit() after Parse()")
f.Visit(visitor)
fmt.Println("VisitAll() after Parse()")
f.VisitAll(visitor)
}
Something along the lines of the setup they have but then adding a
int_val := f.get("int")
to get the named argument would seem more useful. I'm completely new to Go, so just trying to get acquainted with the language.
答案1
得分: 57
这是一个使用flag
包的复杂示例。通常情况下,标志是这样设置的:
package main
import "flag"
// 注意,变量是指针类型
var strFlag = flag.String("long-string", "", "描述")
var boolFlag = flag.Bool("bool", false, "标志的描述")
func init() {
// 使用短标志设置长标志的示例
flag.StringVar(strFlag, "s", "", "描述")
}
func main() {
flag.Parse()
println(*strFlag, *boolFlag)
}
英文:
This is complicated example of using flag
package. Typically flags set up this way:
package main
import "flag"
// note, that variables are pointers
var strFlag = flag.String("long-string", "", "Description")
var boolFlag = flag.Bool("bool", false, "Description of flag")
func init() {
// example with short version for long flag
flag.StringVar(strFlag, "s", "", "Description")
}
func main() {
flag.Parse()
println(*strFlag, *boolFlag)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论