Parse Positional Args With flag.FlagSet

Bind flags and positional arguments to an isolated flag.FlagSet: Parse splits flags from trailing operands and Args, NArg, and Arg expose the rest.

GoCli Tooling

Code

gosnippet
26 lines
package main

import (
	"flag"
	"fmt"
)

func main() {
	// 独立 FlagSet:便于测试与子命令复用,不污染全局 flag.CommandLine
	fs := flag.NewFlagSet("deploy", flag.ContinueOnError)
	env := fs.String("env", "dev", "target environment")
	replicas := fs.Int("replicas", 1, "instance count")

	// 参数列表像真实命令行:先旗标,后位置参数
	args := []string{"-env", "prod", "-replicas", "3", "api", "worker"}
	if err := fs.Parse(args); err != nil {
		panic(err)
	}

	fmt.Println("env:", *env)
	fmt.Println("replicas:", *replicas)

	// Parse 之后:fs.Args() 是剩下的位置参数
	fmt.Println("positional:", fs.Args())
	fmt.Println("count:", fs.NArg(), "first:", fs.Arg(0))
}

Inside the snippet

Parse Positional Args With flag.FlagSet reduces to the function main.

Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err).

What to watch for

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Using it

The demo output is labeled (env:, replicas:, positional:), so each printed line points back to the operation that produced it.

The key statements, annotated

args := []string{"-env", "prod", "-replicas", "3", "api", "worker"}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does Parse Positional Args With flag.FlagSet print when run?
Invoke the file as-is — the `env:`, `replicas:`, `positional:` prefixes identify which step printed each line.