Global flags, flag.Parse

827 views
Skip to first unread message

Albert Strasheim

unread,
Jan 17, 2012, 9:08:20 AM1/17/12
to golang-nuts
Hello all

I was wondering if flag.Bool shouldn't do:

func Bool(name string, value bool, usage string) *bool {
checkParsed()
return commandLine.Bool(name, value, usage)
}

func checkParsed() {
if Parsed() {
panic("Adding a flag after global flags were parsed")
}
}

Parse's documentation says:

Must be called after all flags are defined and before flags are
accessed by the program.

If you misuse the flag package and the global flag set, flags defined
after calling Parse just aren't filled in. Would anyone want this in a
correct program?

Regards

Albert

unread,
Jan 17, 2012, 10:13:09 AM1/17/12
to golang-nuts
I think it is intuitive that functions such as flag.Bool() need to be
called before flag.Parse() is called.

Albert Strasheim

unread,
Jan 17, 2012, 10:45:50 AM1/17/12
to golang-nuts
Hello

On Jan 17, 5:13 pm, ⚛ <0xe2.0x9a.0...@gmail.com> wrote:
> I think it is intuitive that functions such as flag.Bool() need to be
> called before flag.Parse() is called.

I agree, but things get more interesting when you have many developers
and a large codebase with lots of packages defining flags and two
functions that might choose to take it upon themselves to call
flag.Parse.

Regards

Albert

Jan Mercl

unread,
Jan 17, 2012, 10:54:25 AM1/17/12
to golan...@googlegroups.com
On Tuesday, January 17, 2012 4:45:50 PM UTC+1, Albert Strasheim wrote:
I agree, but things get more interesting when you have many developers
and a large codebase with lots of packages defining flags and two
functions that might choose to take it upon themselves to call
flag.Parse.

I think no package intended for general use should ever call flag.Parse. That's IMO a task for main() or init() in package main only.

Paul Borman

unread,
Jan 17, 2012, 11:33:15 AM1/17/12
to golan...@googlegroups.com
A corollary is that all the flag.Type() functions in packages should be placed in an init routine and flag.TypeVar() called from an init routine or assigned to a global variable.

Russ Cox

unread,
Jan 23, 2012, 1:04:55 PM1/23/12
to Albert Strasheim, golang-nuts
On Tue, Jan 17, 2012 at 09:08, Albert Strasheim <ful...@gmail.com> wrote:
> Would anyone want this in a
> correct program?

You are allowed to call flag.Parse, look at flag.Args(0),
add more flags, change os.Args, and call flag.Parse again.
I have used this when implementing commands that
have subcommands.

Russ

Reply all
Reply to author
Forward
0 new messages