Why use package variables for "flag" values?

I’m reading The Go Programming Language, and in all the examples I’ve seen using the flag package, package-level variables are used to hold the flags. Examples:

The forum won’t let me make this a link, but here’s another: https://github.com/adonovan/gopl.io/blob/master/ch7/sleep/sleep.go#L16

My question is, why? Making it a package variable is non-obvious to me. The examples seem to work just as well if I move the declarations into main().

Thanks in advance for any insight!

It makes it easier to do something like

var db string

func main() {
      flag.StringVar(*db, "db", "localhost:3389", "database host")
      flag.Parse()
      processData()
}

func processData() {
      conn, err := openDatabaseConnection(db, ...)
      ...
}

IMO, it’s clearer to explicitly pass db into processData and scope the declaration of db to the same function that calls flag.StringVar

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.