什么时候真正需要将 Go 源代码放在 $GOPATH/src 中?

Lon*_*ner 8 projects-and-solutions directory-structure go

看一下这个 shell 会话,我在其中用 Go 构建了一个简单的 hello world 程序。

$ cd ~/lab/hello/
$ ls
hello.go
$ cat hello.go 
package main

import "fmt"

func main() {
    fmt.Printf("hello, world\n")
}
$ go build
$ ./hello 
hello, world
$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH=""
GORACE=""
GOROOT="/usr/lib/go"
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 8.7 (jessie)
Release:    8.7
Codename:   jessie
Run Code Online (Sandbox Code Playgroud)

这是我不明白的地方。https://golang.org/doc/install#testing上的教程说我应该将hello.go文件放在 ~/go/src/hello 中。但我不遵循这个。那么我的程序编译得怎么样?如果我的程序以这种方式编译得很好,为什么文档说我应该将源代码保存在 ~/go/src 或 $GOPATH/src 中,而这似乎并不重要?

有没有一种场景确实需要将源代码放在 $GOPATH/src 下?

pet*_*rSO 4

标准 Go 工具在$GOPATH子目录srcpkg和中查找bin。例如,

currency.go

package main

import (
    "fmt"
    "time"

    "golang.org/x/text/currency"
)

func main() {
    t1799, _ := time.Parse("2006-01-02", "1799-01-01")
    for it := currency.Query(currency.Date(t1799)); it.Next(); {
        from := ""
        if t, ok := it.From(); ok {
            from = t.Format("2006-01-01")
        }
        fmt.Printf("%v is used in %v since: %v\n", it.Unit(), it.Region(), from)
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ go build currency.go
currency.go:7:2: cannot find package "golang.org/x/text/currency" in any of:
    /home/peter/go/src/golang.org/x/text/currency (from $GOROOT)
    /home/peter/gopath/src/golang.org/x/text/currency (from $GOPATH)
$ 
Run Code Online (Sandbox Code Playgroud)

如果我们将丢失的包放入 中$GOPATH/src,标准 Go 工具就会找到它。

$ go get golang.org/x/text/currency
$ go build currency.go
$ ./currency
GBP is used in GB since: 1694-07-07
GIP is used in GI since: 1713-01-01
USD is used in US since: 1792-01-01
$ 
Run Code Online (Sandbox Code Playgroud)