Removing example usage of init() from pkg.Flag docs page?

76 views
Skip to first unread message

crod...@gmail.com

unread,
Jan 26, 2022, 10:46:34 PM1/26/22
to golang-nuts
On this page:


There is an example:

var flagvar int func init() { flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") }

I understand that this is only an example, but there is no real need to
use an init() function when using the flag package.

When I first read this doc, I thought that using an init() function
was a requirement for the flag package. Other people may share the
same misunderstanding, because 2 years ago I ran into this usage pattern
in a third party library, and ran into problems when trying to compile the
library with a newer Go tool chain.

I mentioned that problem on this list:

Would it be ok if I submit a patch to the docs to remove the init()

If people use the flag package from inside an init() function and it works for them,
that won’t change, since I am not proposing a code change.
Removing init() from the example may reduce confusion for other people
who might have the same confusion that I did.

Craig

Ian Lance Taylor

unread,
Jan 26, 2022, 11:10:08 PM1/26/22
to crod...@gmail.com, golang-nuts
That example is under the text "If you like, you can bind the flag to
a variable using the Var() functions." It immediately follows an
example that does not use an init function. Although you don't have
to use an init function with the flag package, you do have to use one
if you want to bind the flag to a variable. While no doubt the
documentation can be improved, I don't think we should simply remove
the example of using an init function.

Ian
Reply all
Reply to author
Forward
0 new messages