Search code examples
gogo-flag

Golang flag: Ignore missing flag and parse multiple duplicate flags


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

Solution

  • 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