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.

GoCli Tooling

Code

gosnippet
44 lines
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 err before 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

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:`.