Skip to content

fix: initialize default Usage function on NewFlagSet and Init - #518

Open
AdamMagued wants to merge 2 commits into
spf13:masterfrom
AdamMagued:fix-newflagset-default-usage
Open

AdamMagued wants to merge 2 commits into
spf13:masterfrom
AdamMagued:fix-newflagset-default-usage

Conversation

@AdamMagued

Copy link
Copy Markdown

Problem

In the Go standard library flag package, calling flag.NewFlagSet(name, errorHandling) initializes f.Usage to point to a default usage printer.
In spf13/pflag, NewFlagSet and Init leave f.Usage uninitialized (nil). Consequently, if user code or third-party libraries create a FlagSet and invoke f.Usage(), the program panics with a nil pointer dereference.

Root Cause

NewFlagSet and FlagSet.Init did not assign a default function to f.Usage. While internal methods like f.usage() had a fallback when f.Usage was nil, direct invocations of the exported f.Usage field resulted in a nil function call panic.

Solution

  1. In flag.go, update NewFlagSet and Init to initialize f.Usage = func() { defaultUsage(f) }, matching Go standard library flag behavior.
  2. In flag_test.go, add TestNewFlagSetDefaultUsage and TestFlagSetInitDefaultUsage to verify that newly constructed flag sets have a non-nil Usage function that prints the expected usage output without panicking.

Verification

  • Ran full test suite in container sandbox (go test -v ./...); all tests pass.
  • Verified specific unit tests for both NewFlagSet and FlagSet.Init.

Fixes #253

@CLAassistant

CLAassistant commented Oct 2, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Comment thread flag.go
…nd Init

Reflect default Usage behavior in docstrings as requested in review.
@AdamMagued

Copy link
Copy Markdown
Author

Updated in 9c50e03: added docstrings for FlagSet.Usage, NewFlagSet, and FlagSet.Init documenting the default Usage function initialization as requested in review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Usage function is not defined when creating a new flag set

3 participants