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.
Code
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
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 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.