dongwo5110 2017-04-19 14:26
浏览 571
已采纳

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

Take a look at this shell session, where I build a simple hello world program in Go.

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

import "fmt"

func main() {
    fmt.Printf("hello, world
")
}
$ 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

Here is what I don't understand. The tutorial at https://golang.org/doc/install#testing says that I should place my hello.go file at ~/go/src/hello. But I am not following this. How is my program compiling then? If my program is compiling fine in this manner, why does the documentation say that I should keep my source code at ~/go/src or $GOPATH/src when it does not seem to matter?

Is there a scenario where it is really necessary to place the source code at $GOPATH/src?

  • 写回答

3条回答 默认 最新

  • dongpo5264 2017-04-19 15:29
    关注

    The standard Go tools look in the $GOPATH subdirectories src, pkg, and bin. For example,

    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
    ", it.Unit(), it.Region(), from)
        }
    }
    

    Output:

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

    If we put the missing package in $GOPATH/src, the standard Go tools will find it.

    $ 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
    $ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题