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

Go

Go Problem Overview


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 

Go Solutions


Solution 1 - Go

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()
}

Solution 2 - Go

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"]

Solution 3 - Go

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().

Solution 4 - Go

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSidharth C. NadhanView Question on Stackoverflow
Solution 1 - GoserejjaView Answer on Stackoverflow
Solution 2 - GoPylinuxView Answer on Stackoverflow
Solution 3 - GofuzView Answer on Stackoverflow
Solution 4 - GoarithmeticsxView Answer on Stackoverflow