我正在尝试使用flag包。我的整个问题是我需要为同一参数指定组/多个值。 例如,我需要解析一个命令,如下所示:
go run mycli.go -action first -point 10 -action
second -point 2 -action 3rd -point something
我需要检索每组动作/点参数。可能吗?
答案 0 :(得分:1)
package main
import (
"flag"
"fmt"
"strconv"
)
// Define a type named "intslice" as a slice of ints
type intslice []int
// Now, for our new type, implement the two methods of
// the flag.Value interface...
// The first method is String() string
func (i *intslice) String() string {
return fmt.Sprintf("%d", *i)
}
// The second method is Set(value string) error
func (i *intslice) Set(value string) error {
fmt.Printf("%s\n", value)
tmp, err := strconv.Atoi(value)
if err != nil {
*i = append(*i, -1)
} else {
*i = append(*i, tmp)
}
return nil
}
var myints intslice
func main() {
flag.Var(&myints, "i", "List of integers")
flag.Parse()
}
参考:http://lawlessguy.wordpress.com/2013/07/23/filling-a-slice-using-command-line-flags-in-go-golang/
答案 1 :(得分:0)
旗帜套餐不会帮助你。最接近你的是os包:
[jadekler@Jeans-MacBook-Pro:~/go/src]$ go run temp.go asdasd lkjasd -boom bam -hello world -boom kablam
[/var/folders/15/r6j3mdp97p5247bkkj94p4v00000gn/T/go-build548488797/command-line-arguments/_obj/exe/temp asdasd lkjasd -boom bam -hello world -boom kablam]
因此,第一个运行时标志键是os.Args [1],值是os.Args [2],下一个键是os.Args [3],依此类推。