多文件的包在golang中是如何工作的?

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

How do packages with multiple files work in golang?

问题

这个仓库有3个go文件,都以“package lumber”开头。
要使用这个包,我应该将它放在我的GOROOT中,然后在我的程序中简单地导入它。

import lumber

在这个包中,变量和类型如何在多个文件中相互连接?Go编译器如何知道从哪个文件开始读取?

如果我想阅读这个包,我应该从哪里开始阅读以理解这个包?这里的流程是什么?

英文:

This repo has 3 go files all begin with "package lumber".
To use this package, I'm supposed to put this in my GOROOT and simply

import lumber

in my program. How do variables and types in this package connect with each other across multiple files? How does the go compiler know which file to begin reading first?

In case I want to read the package, where should I begin reading to understand the package? What exactly is the flow of things here?

答案1

得分: 23

为了详细说明jnml的答案:

当你在代码中使用import "foo/bar"时,你并不是在引用源文件(源文件位于$GOPATH/src/foo/bar/)。

相反,你引用的是一个已编译的包文件,位于$GOPATH/pkg/$GOOS_$GOARCH/foo/bar.a。当你构建自己的代码时,如果编译器发现foo/bar包尚未被编译(或已过期),它会自动为你完成这个过程。

它通过将$GOPATH/src/foo/bar目录中的所有相关源文件汇总到一个单独的bar.a文件中来实现这一点,并将其安装在pkg目录中。然后编译过程继续进行。

这个过程对所有导入的包以及被这些包导入的包都会重复进行,一直延伸到依赖链的最底层。

*) 文件如何被汇总取决于文件本身的命名方式以及其中存在的构建标签。

要更深入地了解这个过程的工作原理,请参考构建文档

英文:

To elaborate on jnml's answer:

When you use import "foo/bar" in your code, you are not referring to the source files (which will be located in $GOPATH/src/foo/bar/).

Instead, you are referring to a compiled package file at $GOPATH/pkg/$GOOS_$GOARCH/foo/bar.a. When you build your own code, and the compiler finds that the foo/bar package has not yet been compiled (or is out of date), it will do this for you automatically.

It does this by collating* all the relevant source files in the $GOPATH/src/foo/bar directory and building them into a single bar.a file, which it installs in the pkg directory. Compilation then resumes with your own program.

This process is repeated for all imported packages, and packages imported by those as well, all the way down the dependency chain.

*) How the files are collated, depends on how the file itself is named and what kind of build tags are present inside it.

For a deeper understanding of how this works, refer to the build docs.

答案2

得分: 15

不,你不应该将这个放在我的GOROOT中。你应该执行

$ go get github.com/jcelliott/lumber

这将把存储库克隆到$GOPATH/src/github.com/jcelliott/lumber。然后你可以通过在代码中导入它来使用该包

import "github.com/jcelliott/lumber"

关于作用域规则:声明和作用域

英文:

No, you're not "supposed to put this in my GOROOT". You're supposed to execute

$ go get github.com/jcelliott/lumber

which will clone the repository into $GOPATH/src/github.com/jcelliott/lumber. Then you can use the package by importing it in your code as

import "github.com/jcelliott/lumber"

About the scoping rules: Declarations and scope

huangapple
  • 本文由 发表于 2013年6月5日 14:35:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/16933094.html
匿名

发表评论

匿名网友

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

确定