duanke9540 2013-10-07 20:48
浏览 45

去构建vs去构建file.go

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
  • 写回答

1条回答 默认 最新

  • doujie1917 2013-10-08 05:55
    关注

    I asked this question on the google group site for golang and here's one of the responses.

    go build file.go (even if file.go is in GOPATH) 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 the go 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() {
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向