英文:
How to define group of flags in go?
问题
我正在尝试使用flag包。我的问题是,我需要为同一个参数指定多个组/多个值。
例如,我需要解析以下命令:
go run mycli.go -action first -point 10 -action second -point 2 -action 3rd -point something
我需要获取每个action/point参数组。这可能吗?
英文:
I'm trying to make use of the flag package. My whole issue is that I need to specify groups/multiple values for the same parameter.
For example I need to parse a command as below:
go run mycli.go -action first -point 10 -action
second -point 2 -action 3rd -point something
I need to retrieve each group of action/point param. Is it possible?
答案1
得分: 1
包 main
import (
"flag"
"fmt"
"strconv"
)
// 定义一个名为 "intslice" 的类型,作为 int 的切片
type intslice []int
// 现在,对于我们的新类型,实现 flag.Value 接口的两个方法...
// 第一个方法是 String() string
func (i *intslice) String() string {
return fmt.Sprintf("%d", *i)
}
// 第二个方法是 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", "整数列表")
flag.Parse()
}
参考:http://lawlessguy.wordpress.com/2013/07/23/filling-a-slice-using-command-line-flags-in-go-golang/
英文:
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()
}
Ref: http://lawlessguy.wordpress.com/2013/07/23/filling-a-slice-using-command-line-flags-in-go-golang/
答案2
得分: 0
flag
包对你没有帮助。你可以使用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]
,依此类推。
英文:
The flag package won't help you. Closest you'll get is the os package:
[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]
So, the first runtime flag key would be os.Args1, the value would be os.Args[2], the next key would be os.Args[3], and so on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论