Standard library / flag
flag.FlagSet.Var()
Registers a custom flag.Value; the example accumulates repeated values in a slice. Run with arguments: ["-tag=a", "-tag=b"]. Expected stdout: 'a,b\n'.
Formal Syntax & Structure
go syntaxgo
func (f *FlagSet) Var(value Value, name string, usage string)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| value | Value | Default value for registration, or text to parse for Set. |
| name | string | Name of the flag or flag set. |
| usage | string | Help text describing the flag. |
Working Example
Example Snippetgo
package main
import ( "flag" "fmt" "os" "strings")
func check(e error) { if e != nil { panic(e) }}
type tagList []string
func (t *tagList) String() string { if t == nil { return "" } return strings.Join(*t, ",")}func (t *tagList) Set(s string) error { *t = append(*t, s); return nil }
func main() { f := flag.NewFlagSet("demo", flag.ContinueOnError) var tags tagList f.Var(&tags, "tag", "tag") check(f.Parse(os.Args[1:])) fmt.Println(tags.String())}