What's the difference between go build
and go build file.go
?
I'm asking because when I run go build
on a package that imports a local package, then I get this error message.
can't load package: C:\go\src\bug\main.go:3:8: local import "./local_file" in non-local package
However, when I specify a file name it works. Ex go build main.go
Console history on Windows XP.
C:\gopath\src\bug:>go version
go version go1.1 windows/386
C:\gopath\src\bug:>dir
...
<DIR> local_file
55 main.go
...
C:\gopath\src\bug:>type main.go
package main
import _ "./local_file"
func main() {
}
C:\gopath\src\bug:>type local_file\local_file.go
package local_file
import "fmt"
func init() {
fmt.Println("Called: local_file.init()")
}
C:\gopath\src\bug:>go run main.go
Called: local_file.init()
C:\gopath\src\bug:>go build main.go
C:\gopath\src\bug:>dir
...
<DIR> local_file
1,285,120 main.exe
55 main.go
...
C:\gopath\src\bug:>go build
can't load package: C:\gopath\src\bug\main.go:3:8: local import "./local_file" in non-local package
I asked this question on the google group site for golang and here's one of the responses.
go build file.go
(even iffile.go
is inGOPATH
) isn't building a package in a workspace, so it follows doesn't follow that rule. The downside is that you have to name all the*.go
files, you don't get some of the automatic behaviour of thego
command (eg: testing & installing), and you can't build a package (which requires installing), only executables. Also, it's not go-gettable.The "
go build file.go
" should only ever be used for simple one source file binaries that you don't intend to ever distribute or re-use code from. Even then, it's often simpler and faster to follow the go tool's conventions: one package per folder (and vice versa) no relative imports (ever) "go run file.go
" follows the same logic, and is even less recommended.Both patterns are meant for very specific uses, and should be avoided in regular programs and packages.
By: Carlos Castillo
So it turns out that Google Go enforces the import path for packages to be relative to the src
directory in the environmental variables GOROOT
or GOPATH
.
Thus here's the fix to make the program build with go build
.
Note: GOPATH
is set to C:\gopath
Change main.go
from
package main
import _ "./local_file"
func main() {
}
To this
package main
import _ "bug/local_file"
func main() {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With