flag.Func Inline Flag Callbacks
Register a flag whose parsing logic is a plain callback with flag.Func, so repeatable values accumulate without a custom flag.Value type.
Code
package main
import (
"errors"
"flag"
"fmt"
"strings"
)
func main() {
var hosts []string
dryRun := false
fs := flag.NewFlagSet("deploy", flag.ContinueOnError)
fs.BoolVar(&dryRun, "dry-run", false, "print the plan without running it")
// flag.Func:解析逻辑内联成回调,不必再定义 flag.Value 类型
fs.Func("host", "repeatable target host", func(value string) error {
value = strings.TrimSpace(value)
if value == "" {
return errors.New("host must not be empty")
}
hosts = append(hosts, value)
return nil
})
// 同一 flag 出现两次,回调就被调用两次
err := fs.Parse([]string{"-dry-run", "-host", "api-1", "-host", " api-2 "})
if err != nil {
fmt.Println("parse error:", err)
return
}
fmt.Println("dry run:", dryRun)
fmt.Println("hosts:", hosts)
fmt.Println("positional args:", fs.Args())
// 回调返回错误时 Parse 直接失败,值也不会被追加
bad := flag.NewFlagSet("bad", flag.ContinueOnError)
bad.Func("host", "target host", func(value string) error {
return errors.New("rejected: " + value)
})
fmt.Println("bad parse err non-nil:", bad.Parse([]string{"-host", "x"}) != nil)
}Callback wiring under the hood
The snippet is organized around the function main.
Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.
Watch out for
- Zero packages pulled in — the runtime ships every API this code touches.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
Entry signature: func main()
The file’s steps show up in the output as parse error:, dry run:, hosts:.
Statements that gate parsing
return errors.New("host must not be empty")
return errors.New("rejected: " + value)
if err != nil {
fmt.Println("parse error:", err)
return
}
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 is the error handling style?
- By return value: each fallible call hands back an `error`, checked at 1 place here.
- What does flag.Func Inline Flag Callbacks print when run?
- Running the file directly is enough — expect labeled output lines such as `parse error:`, `dry run:`, `hosts:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.