From d299f4e332419effcc5e164d186e227362585352 Mon Sep 17 00:00:00 2001 From: Shirong Lu <73147033+happysnaker@users.noreply.github.com> Date: Fri, 3 Jul 2026 16:28:32 +0800 Subject: [PATCH] docs: clarify SortFlags example with complete runnable program The existing SortFlags example used 'flags.SortFlags' without showing that SortFlags is a field on FlagSet, not a package-level variable. This led to confusion for users who tried to use pflag.SortFlags directly. Updated the example to show a complete program using NewFlagSet, and added a separate note for the CommandLine case. Fixes #456 --- README.md | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index da27cec6..0c8b00d4 100644 --- a/README.md +++ b/README.md @@ -250,13 +250,35 @@ flags.MarkHidden("secretFlag") ## Disable sorting of flags `pflag` allows you to disable sorting of flags for help and usage message. +`SortFlags` is a field on `FlagSet`, not a package-level variable. To disable +sorting on the default `CommandLine` flag set, use `pflag.CommandLine.SortFlags`. + **Example**: ```go -flags.BoolP("verbose", "v", false, "verbose output") -flags.String("coolflag", "yeaah", "it's really cool flag") -flags.Int("usefulflag", 777, "sometimes it's very useful") -flags.SortFlags = false -flags.PrintDefaults() +package main + +import ( + "fmt" + + "github.com/spf13/pflag" +) + +func main() { + flags := pflag.NewFlagSet("example", pflag.ContinueOnError) + flags.BoolP("verbose", "v", false, "verbose output") + flags.String("coolflag", "yeaah", "it's really cool flag") + flags.Int("usefulflag", 777, "sometimes it's very useful") + flags.SortFlags = false + flags.PrintDefaults() + fmt.Println() +} +``` + +For the default `CommandLine` flag set: + +```go +pflag.CommandLine.SortFlags = false +pflag.PrintDefaults() ``` **Output**: ```