Skip to content

flag: antipattern - failf error handler prints usage unconditionally #73307

@abitrolly

Description

@abitrolly

Go version

1.24

Output of go env in your module/workspace:

No.

What did you do?

Minimal flags example (https://go.dev/play/p/r6dDUoerjTI):

package main

import "flag"

func main() {
        flag.Parse()
}

Running this example with invalid flag always prints usage that is impossible to turn off regardless of error handling strategy https://pkg.go.dev/flag#ErrorHandling

What did you see happen?

$ go run minimal.go -ggg
flag provided but not defined: -ggg
Usage of /home/anatoli/.cache/go-build/8d/8dae0dadd55b6ae9e6d4bca4d6c85e20970b537337a98a5006eaeef926f92b5f-d/minimal:
exit status 2

The problem is in failf function https://cs.opensource.google/go/go/+/refs/tags/go1.24.2:src/flag/flag.go;l=1060 that outputs the usage two levels below Parse where it should be handled.

Parse --> parseOne --> failf --> usage

The similar report #63977

What did you expect to see?

At least some way to suppress usage message in errors.

Right now the only way to do this is to completely turn off all flag output and handle it all manually.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions