繁体   English   中英

如何在go中定义标志组?

[英]How to define group of flags in go?

我正在尝试使用标志包。 我的整个问题是,我需要为同一参数指定组/多个值。 例如,我需要解析如下命令:

 go run mycli.go -action first -point 10 -action
 second -point 2 -action 3rd -point something

我需要检索每组动作/点参数。 可能吗?

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/

标志包对您没有帮助。 最接近的是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],依此类推。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM