Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang flag: Ignore missing flag and parse multiple duplicate flags

Tags:

go

go-flag

I am new to Golang and I have been unable to find a solution to this problem using flag.

How can I use flag so my program can handle calls like these, where the -term flag may be present a variable number of times, including 0 times:

./myprogram -f flag1
./myprogram -f flag1 -term t1 -term t2 -term  t3
like image 421
matt Avatar asked Aug 03 '17 14:08

matt


1 Answers

You need to declare your own type which implements the Value interface. Here is an example.

// Created so that multiple inputs can be accecpted
type arrayFlags []string

func (i *arrayFlags) String() string {
    // change this, this is just can example to satisfy the interface
    return "my string representation"
}

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

then in the main function where you are parsing the flags

var myFlags arrayFlags

flag.Var(&myFlags, "term", "my terms")
flag.Parse()

Now all the terms are contained in the slice myFlags

like image 187
reticentroot Avatar answered Oct 28 '22 19:10

reticentroot