Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

golang flag 包子命令如何确定实际输入的 flag?

例如 fooCmd 子命令有多个 flag

fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
fooA := fooCmd.String("a", "0", "a")
fooB := fooCmd.String("b", "0", "b")
// ... flag 可以有多个

fooCmd.Parse(os.Args[2:])

// 如何判断?
if 仅有 a flag {
    A()
} else if 仅有 b flag {
    B()
} else if 同时有 a 和 b {
    AB()
} else {
    X()
}

调用

> go run test.go foo
X()
> go run test.go foo -a 10
A()
> go run test.go foo -a 10 -b 20
AB()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

使用 visit() 方法遍历 flag

    fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
    fooA := fooCmd.String("a", "-1", "a")
    fooB := fooCmd.String("b", "-1", "b")
    fooC := fooCmd.Bool("c", false, "c")
    // ... flag 可以有多个

    fooCmd.Parse(os.Args[2:])

    fmt.Println("a:", *fooA)
    fmt.Println("b:", *fooB)
    fmt.Println("c:", *fooC)

    // 遍历定义好的 flag
    fooCmd.VisitAll(func(f *flag.Flag) {
        if f.Value.String() != f.DefValue {
            fmt.Printf("%s = %s [default = %s]
", f.Name, f.Value.String(), f.DefValue)
        } else {
            fmt.Printf("%s = %s
", f.Name, f.Value.String())
        }
    })

    fmt.Println()

    // 遍历实际传入的 flag
    fooCmd.Visit(func(f *flag.Flag) {
        if f.Value.String() != f.DefValue {
            fmt.Printf("%s = %s [default = %s]
", f.Name, f.Value.String(), f.DefValue)
        } else {
            fmt.Printf("%s = %s
", f.Name, f.Value.String())
        }
    })

    // 额外的参数
    fmt.Println(fooCmd.Args())
>go run test.go foo -a 10 -c xxx

a: 10
b: -1
c: true

a = 10 [default = -1]
b = -1
c = true [default = false]

a = 10 [default = -1]
c = true [default = false]

[xxx]

不知道还有没有更好的方法了


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...