Package visibility

Regardless of the number of source files declared to be part of a package, all source code elements (types, variables, constants, and functions), declared at a package level, share a common scope. Therefore, the compiler will not allow an element identifier to be re-declared more than once in the entire package. Let us use the following code snippets to illustrate this point, assuming both source files are part of the same package $GOPATH/src/foo:

package foo   
   
var (   
  bar int = 12   
)   
   
func qux () {   
  bar += bar   
}   

foo/file1.go

package foo   
   
var bar struct{   
  x, y int   
}   
   
func quux() {   
  bar = bar * bar   
}   

foo/file2.go

Illegal variable identifier re-declaration

Although they are in two separate files, the declaration of variables with identifier ...

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.