Standard library / flag

flag.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 Var(value Value, name string, usage string)

Parameters & Attributes

NameTypeDescription
valueValueDefault value for registration, or text to parse for Set.
namestringName of the flag or flag set.
usagestringHelp text describing the flag.

Working Example

Example Snippetgo
package main
import (  "flag"  "fmt"  "strings")
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() {  var tags tagList  flag.Var(&tags, "tag", "tag")  flag.Parse()  fmt.Println(tags.String())}
Go Reference