Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang undefined variable

Tags:

undefined

go

I have 2 go files:

/Users/username/go/src/Test/src/main/Test.go

package main

import "fmt"

func main() {
    fmt.Printf(SomeVar)
}

and file /Users/username/go/src/Test/src/main/someFile.go

package main

const SomeVar = "someFile"

However I am constantly getting compiler error:

/Users/username/go/src/Test/src/main/Test.go:6: undefined: SomeVar

Can someone explain to me why is SomeVar labeled as undefined?

like image 588
Dave Avatar asked Jul 05 '14 02:07

Dave


3 Answers

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 :)

like image 75
Para Avatar answered Oct 18 '22 14:10

Para


Try

go run Test.go someFile.go
like image 16
theaidem Avatar answered Oct 18 '22 16:10

theaidem


Quote:

I think you're misunderstanding how the go tool works. You can do "go build" in a directory, and it'll build the whole package (a package is defined as all .go files in a directory). Same for go install, go test, etc. Go run is the only one that requires you to specify specific files... it's really only meant to be used on very small programs, which generally only need a single file.

So do:

go build && ./program_name

See also

like image 11
warvariuc Avatar answered Oct 18 '22 14:10

warvariuc