If a flag is redefined, go only tells one of the places where the flag is redefined. Is there a way to identify at which place the other flag is defined?
Just to give an instance, see the below program. Here in foo.go
, the first flag is defined. Say if I am trying to add a flag with the same name in package main
, go panic tells me that the flag is already defined (as package foo
was initialized first) and I am redefining it in package main
.
This is a simple example but in a large code-base where the flag could be defined in imported libraries, its hard to find out where the flag is first defined. Any way to find this out?
package main
import (
"flag"
"play.ground/foo"
)
func main() {
var tf string
flag.StringVar(&tf, "tf", "", "")
foo.Bar()
}
-- go.mod --
module play.ground
-- foo/foo.go --
package foo
import (
"flag"
"fmt"
)
func init() {
var tf string
flag.StringVar(&tf, "tf", "", "")
}
func Bar() {
fmt.Println("This function lives in an another file!")
}
panic :
/tmpfs/play flag redefined: tf
panic: /tmpfs/play flag redefined: tf
goroutine 1 [running]:
flag.(*FlagSet).Var(0xc0000960c0, {0x4c3148, 0xc0000980a0}, {0x4a2642, 0x2}, {0x0, 0x0})
/usr/local/go-faketime/src/flag/flag.go:980 +0x2f9
flag.StringVar(...)
/usr/local/go-faketime/src/flag/flag.go:851
main.main()
/tmp/sandbox3734065722/prog.go:11 +0x7d
Program exited.
playground :https://go.dev/play/p/jsmMcnEO2hy个