3

Golang项目代码组织的一些总结

 3 years ago
source link: https://studygolang.com/articles/32474
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

import

  • import的是目录,import时会从GOROOT中搜索包(标准包)或从GOPATH/src下搜索包,如果GOPATH有多个,则从第一个开始,直到找到包。import也可以不依赖GOPATH,使用相对路径引入,相对于main包的路径。
  • package包名是调用包的时候使用,一般建议package包名与包所有的目录保持一致。

go get

  • go get 会下载包的代码包并编译包(.a文件)
  • 如果GOPATH有多个,go get 会将代码下载到第一个GOPATH的src目录,包编译到pkg目录

go instal与go build

  • go install 编译并安装包(包括main包),包名为包所在目录,main包(主程序)会安装到bin目录,其它包会安装到pkg目录。
  • go build 只能编辑main包,包名默认为包所在目录,可通过-o参数指定包名。
  • 如果GOPATH中有同名的包,只会在GOPATH中的第一个能go install成功,其它的失失败,报错:
    no install location for $GOPATH/go_2/src/myp: hidden by $GOPATH/go_1/src/myp

GOPATH

  • 允许设置多个路径,和各个系统环境多路径设置一样,windows用“;”,linux(macOS)用“:”分隔。
  • 如果你无需导入外部包且使用相对路径导入自己的代码,代码不一定非要放在GOPATH里,但不推荐这样做.
  • GOPATH的bin、pkg目录会自动创建,src目录放置源代码,也可不创建src,但需import的包能在GOPATH中找到,且go install时会报错:
    go install: no install location for directory GOPATH/m3 outside GOPATH

GOBIN

  • go install main包存放的路径,设置多个时,会被当成一个完整的路径。设置为空时,放在各自GOPATH目录的bin文件夹中(前提是:main包的代码文件不能直接放在GOPATH/src目录下)。
  • GOBIN为空,且main包的代码文件在GOPATH/src目录下时,go install时报错:
    go install: no install location for .go files listed on command line (GOBIN not set)
    go install: no install location for directory $GOPATH/src outside GOPATH For more details see: 'go help gopath'
  • 解决方法:1、设置GOBIN,编译后包名为src。2、将main包代码放在一个目录下,编译后包名为目录名。

有疑问加站长微信联系(非本文作者)

280

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK