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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.