dqrm8199 2017-08-03 14:38
浏览 26
已采纳

Golang标志:忽略丢失的标志并解析多个重复的标志

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
  • 写回答

1条回答 默认 最新

  • doufangyan6862 2017-08-03 20:48
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?