You code is correct:
someFile.go
and Test.go
belong to the same package (main
)
SomeVar
is a const
declared at top level, so it has a package block scope, namely the main
package block scope
- as a consequence,
SomeVar
is visible and can be accessed in both files
(if you need to review scoping in Go, please refer to the Language Specification - Declarations and Scope).
Why do you get an undefined
error then?
You probably launched go build Test.go
or go run Test.go
, both producing the following output, if launched from /Users/username/go/src/Test/src/main
:
# command-line-arguments
./Test.go:6: undefined: SomeVar
You can find the reason here: Command go
If you launch go build
or go run
with a list of .go
files, it treats them as a list of source files specifying a single package, i.e., it thinks there are no other pieces of code in the main
package, hence the error.
The solution is including all the required .go
files:
go build Test.go someFile.go
go run Test.go someFile.go
go build
will also work with no arguments, building all the files it finds in the package as a result:
go build
Note 1: the above commands refer to the local package and, as such, must be launched from the /Users/username/go/src/Test/src/main
directory
Note 2: though other answers already proposed valid solutions, I decided to add a few more details here to help the community, since this is a common question when you start working with Go :)