Go语言如何解决依赖关系的导入?

huangapple go评论68阅读模式
英文:

How does Go import resolving dependencies?

问题

在Go语言中,当我导入一个依赖项时,例如:

import "github.com/spf13/viper"

Go语言会按照以下顺序查找目录:

  1. 当前项目目录(包含导入语句的文件所在的目录)
  2. GOROOT目录(Go语言的安装目录)
  3. GOPATH目录(Go语言的工作目录,用于存放项目和依赖包)

Go语言会按照这个顺序查找依赖包的路径。在这个例子中,Go语言会首先在当前项目目录中查找名为"github.com/spf13/viper"的依赖包。如果找不到,则会继续在GOROOT目录和GOPATH目录中查找。

英文:

In Go, when I import a dependency like:

import "github.com/spf13/viper"

Which directories will Go look into, and in which order?

答案1

得分: 5

查找顺序:

  1. 供应商文件夹。
  2. 标准包。
  3. GOPATH 文件夹。

运行 go help gopath 以了解 Go 如何搜索每个目录。

英文:

Lookup order:

  1. The vendor folder.
  2. The standard packages.
  3. GOPATH folder.

Run go help gopath to learn more on how Go search each directory.

答案2

得分: 2

一个快速简便的方法来查看特定系统中的搜索顺序和确切搜索路径是运行go build err

这将产生类似以下的输出:

无法加载包:包 err 不存在于以下任何位置:
    C:\go\src\err(来自 $GOROOT)
    \\FREENAS\Global Documents\Projects\Go\src\err(来自 $GOPATH)
英文:

A quick and easy way to see the search order and exact paths searched n a particular system is to run go build err.

This produces output similar to this:

can't load package: package err: cannot find package "err" in any of:
    C:\go\src\err (from $GOROOT)
    \\FREENAS\Global Documents\Projects\Go\src\err (from $GOPATH)

huangapple
  • 本文由 发表于 2017年8月8日 10:48:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/45558505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定