Preventing Flag Conflicts in Go

Published: July 18, 2022

Tags:

After import-ing a new package into one of my go projects and attempting to run the build, I was presented the following error:

panic: flag redefined: version

In my project, the version flag allows the user to see what version of the tool they have installed (main.version is passed as the current git tag via -ldflags in the build script).

package main

import (
	"flag"
	"fmt"
)

var version string

func main() {
	ver := flag.Bool("version", false, "Get current version")
	flag.Parse()

	if *ver {
		fmt.Println(ver)
	}
}

Presumably, the problem was that the newly imported package also used a flag with the same name.

The first solution that came to mind was to rename my flag from version to something else (e.g. ver). While this might be a viable approach to fix the issue it was definitely not a desirable one. As such, I reported the issue to the package provider to see if they’d be willing to make any compatibility adjustments on their end to accommodate my use case.

While initially it appeared that my only recourse would be to rename the flag, a clever user responded to my issue, making me aware of the flag.NewFlagSet function. By calling the NewFlagSet function in my code before defining my flags I was able to prevent conflicts with the newly imported package.

package main

import (
	"flag"
	"fmt"
)

var version string

func main() {
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)

	ver := flag.Bool("version", false, "Get current version")
	flag.Parse()

	if *ver {
		fmt.Println(ver)
	}
}

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but loves dabbling in other languages like Go and Ruby. Technical topics that interest me are monitoring, security and performance. I'm also a stickler for good documentation and clear technical writing.

During the day I lead a team of developers and solve challenging technical problems at Rightpoint where I mainly work with the Magento platform. I've also spoken at a number of events.

In my spare time I blog about tech, work on open source and participate in bug bounty programs.

If you'd like to get in contact, you can find me on Twitter and LinkedIn.