panic: runtime error: index out of range [0] with length 0 goroutine 1 [running]: flag.init() /usr/local/go/src/flag/flag.go:1199 +0xfc

https://github.com/golang/go/blob/6d89b38ed86e0bfa0ddaba08dc4071e6bb300eea/src/flag/flag.go#L1199

len(os.Args) > 1 is not always true, at least in Linux and macOS. If you compile a go program and then write a C program to exec it with execl("/path/to/exec", NULL), it will have no arguments at all, not even the executable name

Comment From: seankhliao

This seems like an appropriate panic, the environment violates a fundamental part of what flag needs to work.

Comment From: develerltd

This seems like an appropriate panic, the environment violates a fundamental part of what flag needs to work.

but this is at package level, so its unavoidable? so any package that imports "flag" will crash if the executable is ran like in my example?

that's not an appropriate panic

Comment From: gopherbot

Change https://go.dev/cl/597075 mentions this issue: flag: handle nil os.Args when setting CommandLine at package level Fixes #68340

Comment From: gabyhelp

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)