How to get a list of values into a flag in Golang?

huangapple go评论80阅读模式
英文:

How to get a list of values into a flag in Golang?

问题

Golang中的等效命令是什么?

import "flag"

getList1 := flag.String("getList1", "", "get 0 or more values")
getList2 := flag.String("getList2", "", "get 1 or more values")

flag.Parse()

我注意到flag包允许在Golang中进行参数解析。但是它似乎只支持String、Int或Bool类型。如何以以下格式将值列表传递给flag:

go run myCode.go -getList1 value1 value2
英文:

What is Golang's equivalent of the below python commands ?

import argparse
parser = argparse.ArgumentParser(description="something")
parser.add_argument("-getList1",nargs='*',help="get 0 or more values")
parser.add_argument("-getList2",nargs='?',help="get 1 or more values")

I have seen that the flag package allows argument parsing in Golang.
But it seems to support only String, Int or Bool.
How to get a list of values into a flag in this format :

go run myCode.go -getList1 value1 value2 

答案1

得分: 195

你可以定义自己的flag.Value并使用flag.Var()将其绑定。

示例在这里

然后你可以像下面这样传递多个标志:

go run your_file.go --list1 value1 --list1 value2

更新:为了防止出错,这里包含了代码片段。

package main

import "flag"

type arrayFlags []string

func (i *arrayFlags) String() string {
    return "my string representation"
}

func (i *arrayFlags) Set(value string) error {
    *i = append(*i, value)
    return nil
}

var myFlags arrayFlags

func main() {
    flag.Var(&myFlags, "list1", "Some description for this param.")
    flag.Parse()
}
英文:

You can define your own flag.Value and use flag.Var() for binding it.

The example is here.

Then you can pass multiple flags like following:

go run your_file.go --list1 value1 --list1 value2

UPD: including code snippet right there just in case.

package main

import "flag"

type arrayFlags []string

func (i *arrayFlags) String() string {
	return "my string representation"
}

func (i *arrayFlags) Set(value string) error {
	*i = append(*i, value)
	return nil
}

var myFlags arrayFlags

func main() {
	flag.Var(&myFlags, "list1", "Some description for this param.")
	flag.Parse()
}

答案2

得分: 20

你可以使用flag.Args()函数在命令的末尾至少有一个参数列表。

package main

import (
	"flag"
	"fmt"
)

var one string

func main() {
	flag.StringVar(&one, "o", "default", "arg one")
	flag.Parse()
	tail := flag.Args()
	fmt.Printf("Tail: %+q\n", tail)
}

my-go-app -o 1 this is the rest将打印出Tail: ["this" "is" "the" "rest"]

英文:

You can at least have a list of arguments on the end of you command by using the flag.Args() function.

package main

import (
	"flag"
	"fmt"
)

var one string

func main() {
	flag.StringVar(&one, "o", "default", "arg one")
	flag.Parse()
	tail := flag.Args()
	fmt.Printf("Tail: %+q\n", tail)
}

my-go-app -o 1 this is the rest will print Tail: ["this" "is" "the" "rest"]

答案3

得分: 16

使用flag.String()来获取你需要的参数的整个值列表,然后使用strings.Split()将其拆分为单个项。

英文:

Use flag.String() to get the entire list of values for the argument you need and then split it up into individual items with strings.Split().

答案4

得分: 2

如果在命令行的末尾有一系列整数值,这个辅助函数将正确地将它们转换并放入一个int切片中:

package main

import (
	"flag"
	"fmt"
	"strconv"
)

func GetIntSlice(i *[]string) []int {
	var arr = *i
	ret := []int{}
	for _, str := range arr {
		one_int, _ := strconv.Atoi(str)
		ret = append(ret, one_int)
	}
	return ret
}

func main() {
	flag.Parse()
	tail := flag.Args()
	fmt.Printf("Tail: %T,  %+v\n", tail, tail)
	intSlice := GetIntSlice(&tail)

	fmt.Printf("intSlice: %T,  %+v\n", intSlice, intSlice)

}

mac:demoProject sx$ go run demo2.go 1 2 3 4
Tail: []string,  [1 2 3 4]
intSlice: []int,  [1 2 3 4]

这段代码定义了一个名为GetIntSlice的函数,它接受一个[]string类型的指针作为参数,并返回一个[]int类型的切片。函数内部使用strconv.Atoi函数将字符串转换为整数,并将其添加到结果切片中。在main函数中,我们使用flag包解析命令行参数,并将剩余的参数传递给GetIntSlice函数进行处理。最后,我们打印出结果切片的类型和值。

英文:

If you have a series of integer values at the end of the command line, this helper function will properly convert them and place them in a slice of ints:

package main

import (
	"flag"
	"fmt"
	"strconv"
)

func GetIntSlice(i *[]string) []int {
	var arr = *i
	ret := []int{}
	for _, str := range arr {
		one_int, _ := strconv.Atoi(str)
		ret = append(ret, one_int)
	}
	return ret
}

func main() {
	flag.Parse()
	tail := flag.Args()
	fmt.Printf("Tail: %T,  %+v\n", tail, tail)
	intSlice := GetIntSlice(&tail)

	fmt.Printf("intSlice: %T,  %+v\n", intSlice, intSlice)

}

mac:demoProject sx$ go run demo2.go 1 2 3 4
Tail: []string,  [1 2 3 4]
intSlice: []int,  [1 2 3 4]

huangapple
  • 本文由 发表于 2015年2月4日 21:46:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/28322997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定