flag.Var Accepts Custom Value Types

Implement flag.Value with Set validating each occurrence and String rendering the result, so a single -tag can repeat and accumulate into one slice.

GoCli Tooling

Code

gosnippet
41 lines
package main

import (
	"errors"
	"flag"
	"fmt"
	"strings"
)

// repeatable implements flag.Value: Set handles each -tag occurrence, String renders the value
type repeatable []string

func (r *repeatable) String() string {
	return strings.Join(*r, ",")
}

func (r *repeatable) Set(value string) error {
	if value == "" {
		return errors.New("tag must not be empty")
	}
	*r = append(*r, value)
	return nil
}

func main() {
	fs := flag.NewFlagSet("deploy", flag.ContinueOnError)
	var tags repeatable
	fs.Var(&tags, "tag", "repeatable label, may be given multiple times")
	port := fs.Int("port", 8080, "listen port")

	// Same -tag twice: Set accumulates both into one slice
	if err := fs.Parse([]string{"-tag", "web", "-port", "9090", "-tag", "edge"}); err != nil {
		panic(err)
	}
	fmt.Println("port:", *port)
	fmt.Println("tags:", tags.String())
	fmt.Println("count:", len(tags))

	// Empty value rejected by Set: the flag package surfaces that error to the caller
	fmt.Println("empty rejected:", fs.Parse([]string{"-tag", ""}) != nil)
}

How the snippet works

Count the functions String, Set and main as the entire surface area of flag.Var Accepts Custom Value Types.

Applying it

Entry signature: func (r *repeatable) String() string

The demo output is labeled (port:, tags:, count:), letting each printed line point back to the operation that emitted it.

There are 1 call inside main — String — executed top to bottom.

Statements that decide the outcome

return errors.New("tag must not be empty")
func (r *repeatable) String() string {
return strings.Join(*r, ",")
}

Interactive Tools for This Topic

FAQ

What does flag.Var Accepts Custom Value Types print when run?
Execute the whole file; each printed line is prefixed with a label like `port:`, `tags:`, `count:`.