golang导入包_在Go中导入包
golang导入包
介绍 (Introduction)
There will be times when your code needs additional functionality outside of your current program. In these cases, you can use packages to make your program more sophisticated. A package represents all the files in a single directory on disk. Packages can define functions, types, and interfaces that you can reference in other Go files or packages.
有时您的代码需要当前程序之外的其他功能。 在这些情况下,您可以使用软件包使程序更复杂。 包代表磁盘上单个目录中的所有文件。 包可以定义您可以在其他Go文件或包中引用的功能,类型和接口。
This tutorial will walk you through installing, importing, and aliasing packages.
本教程将指导您完成安装,导入和别名化软件包。
标准库软件包 (Standard Library Packages)
The standard library that ships with Go is a set of packages. These packages contain many of the fundamental building blocks to write modern software. For instance, the fmt
package contains basic functions for formatting and printing strings. The net/http
package contains functions that allow a developer to create web services, send and retrieve data over the http
protocol, and more.
Go附带的标准库是一组软件包。 这些软件包包含编写现代软件的许多基本构件。 例如, fmt
软件包包含用于格式化和打印字符串的基本功能。 net/http
软件包包含允许开发人员创建Web服务,通过http
协议发送和检索数据等功能。
To make use of the functions in a package, you need to access the package with an import
statement. An import
statement is made up of the import
keyword along with the name of the package.
要使用包中的功能,您需要使用import
语句访问包。 import
语句由import
关键字以及包名组成。
As an example, in the Go program file random.go
you can import the math/rand
package to generate random numbers in this manner:
例如,在Go程序文件random.go
您可以导入math/rand
包以这种方式生成随机数:
import "math/rand"
When we import a package, we are making it available in our current program as a separate namespace. This means that we will have to refer to the function in dot notation, as in package.function
.
导入包时,我们将其作为单独的命名空间在当前程序中使用。 这意味着我们将不得不像package . function
那样以点表示法引用该函数package . function
package . function
。
In practice, a function from the math/rand
package could look like these examples:
实际上, math/rand
包中的函数可能类似于以下示例:
-
rand.Int()
which calls the function to return a random integer.rand.Int()
调用函数返回一个随机整数。 -
rand.Intn()
which calls the function to return a random element from0
up to the specified number provided.rand.Intn()
调用该函数以返回从0
到提供的指定数字的随机元素。
Let’s create a for
loop to show how we will call a function of the math/rand
package within our random.go
program:
让我们创建一个for
循环,以展示如何在random.go
程序中调用math/rand
包的random.go
:
package main
import "math/rand"
func main() {
for i := 0; i < 10; i++ {
println(rand.Intn(25))
}
}
This program first imports the math/rand
package on the third line, then moves into a for
loop which that will run 10 times. Within the loop, the program will print a random integer within the range of 0
up to 25
. The integer 25
is passed to rand.Intn()
as its parameter.
该程序首先在第三行上导入math/rand
程序包,然后进入for
循环,该循环将运行10次。 在循环内,程序将打印0
到25
范围内的随机整数。 整数25
作为参数传递给rand.Intn()
。
When we run the program with go run random.go
, we’ll receive 10 random integers as output. Because these are random, you’ll likely get different integers each time you run the program. The output will look something like this:
当我们使用go run random.go
运行程序时,我们将收到10个随机整数作为输出。 由于这些是随机的,因此每次运行该程序时,您可能会获得不同的整数。 输出将如下所示:
Output6
12
22
9
6
18
0
15
6
0
The integers will never go below 0 or above 24.
整数永远不会低于0或高于24。
When importing more than one package, you can use the ()
to create a block. By using a block you can avoid repeating the import
keyword on every line. This will make your code look cleaner:
导入多个软件包时,可以使用()
创建一个块。 通过使用块,可以避免在每一行上重复import
关键字。 这将使您的代码看起来更简洁:
import (
"fmt"
"math/rand"
)
To make use of the additional package, we can now format the output and print out the iteration that each random number was generated on during the loop:
为了使用附加包,我们现在可以格式化输出并打印出在循环期间生成每个随机数的迭代:
package main
import (
"fmt"
"math/rand"
)
func main() {
for i := 0; i < 10; i++ {
fmt.Printf("%d) %d\n", i, rand.Intn(25))
}
}
Now, when we run our program, we’ll receive output that looks like this:
现在,当我们运行程序时,我们将收到如下所示的输出:
Output0) 6
1) 12
2) 22
3) 9
4) 6
5) 18
6) 0
7) 15
8) 6
9) 0
In this section, we learned how to import packages and use them to write a more sophisticated program. So far, we have only used packages from the standard library. Next, let’s see how to install and use packages that are written by other developers.
在本节中,我们学习了如何导入包并使用它们编写更复杂的程序。 到目前为止,我们仅使用了标准库中的软件包。 接下来,让我们看看如何安装和使用由其他开发人员编写的软件包。
安装套件 (Installing Packages)
While the standard library ships with many great and useful packages, they are intentionally designed to be general purpose and not specific in nature. This allows developers to build their own packages on top of the standard library for their own specific needs.
尽管标准库附带了许多很棒且有用的软件包,但它们是有意设计为通用的,而不是本质上特定的。 这使开发人员可以在标准库的顶部构建自己的软件包,以满足自己的特定需求。
The Go tool chain ships with the go get
command. This command allows you to install third party packages to your local development environment and use them in your program.
Go工具链随附go get
命令。 此命令允许您将第三方软件包安装到本地开发环境中,并在程序中使用它们。
When using go get
to install third party packages, it is common for a package to be referenced by its canonical path. That path can also be a path to a public project that is hosted in a code repository such as GitHub. As such, if you want to import the flect
package, you would use the full canonical path:
使用go get
安装第三方软件包时,通常会以其规范路径引用该软件包。 该路径也可以是在诸如GitHub之类的代码存储库中托管的公共项目的路径。 这样,如果要导入flect
包,则应使用完整的规范路径:
- go get github.com/gobuffalo/flect 去获取github.com/gobuffalo/flect
The go get
tool will find the package, on GitHub in this case, and install it into your $GOPATH
.
在这种情况下, go get
工具将在GitHub上找到该软件包,并将其安装到$GOPATH
。
For this example the code would be installed in this directory:
对于此示例,代码将安装在以下目录中:
$GOPATH/src/github.com/gobuffalo/flect
Packages are often being updated by the original authors to address bugs or add new features. When this happens, you may want to use the latest version of that package to take advantage of the new features or resolved bug. To update a package, you can use the -u
flag with the go get
command:
软件包通常由原始作者更新,以解决错误或添加新功能。 发生这种情况时,您可能希望使用该软件包的最新版本来利用新功能或已解决的错误。 要更新软件包,可以在go get
命令中使用-u
标志:
- go get -u github.com/gobuffalo/flect 去获取-u github.com/gobuffalo/flect
This command will also have Go install the package if it is not found locally. If it is already installed, Go will attempt to update the package to the latest version.
如果在本地找不到该命令,该命令还将让Go安装该软件包。 如果已经安装,Go将尝试将软件包更新为最新版本。
The go get
command always retrieves the latest version of the package available. However, there may be updates to previous versions of the package that are still newer than you are using, and would be useful to update in your program. To retrieve that specific version of the package, you would need to use a Package Management tool, such as Go Modules.
go get
命令始终会检索可用软件包的最新版本。 但是,可能会对该软件包的先前版本进行更新,而这些更新仍比您使用的要新,这对于在程序中进行更新很有用。 要检索该特定版本的软件包,您需要使用“ 软件包管理”工具,例如Go Modules 。
As of Go 1.11, Go Modules are used to manage what version of the package you want imported. The topic of package management is beyond the scope of this article, but you can read more about it on the Go Modules GitHub page.
从Go 1.11开始,Go模块用于管理您要导入的软件包的版本。 包管理的主题不在本文讨论范围之内,但是您可以在Go Modules GitHub页面上阅读有关它的更多信息。
别名导入的程序包 (Aliasing Imported Packages)
You may want to change a package name if you have a local package already named the same as a third party package you are using. When this happens, aliasing your import is the best way to handle the collision. You can modify the names of packages and their functions within Go by putting an alias
name in front of the imported package.
如果您的本地软件包已经与您使用的第三方软件包相同的名称,则可能需要更改软件包名称。 发生这种情况时,别名导入将是处理冲突的最佳方法。 您可以通过在导入的软件包前面放置一个alias
在Go中修改软件包的名称及其功能。
The construction of this statement looks like this:
该语句的构造如下所示:
import another_name "package"
In this example, modify the name of the fmt
package in the random.go
program file. We’ll change the package name of fmt
to f
in order to abbreviate it. Our modified program will look like this:
在此示例中,在random.go
程序文件中修改fmt
软件包的名称。 我们将fmt
的软件包名称更改为f
以便缩写。 我们修改后的程序将如下所示:
package main
import (
f "fmt"
"math/rand"
)
func main() {
for i := 0; i < 10; i++ {
f.Printf("%d) %d\n", i, rand.Intn(25))
}
}
Within the program, we now refer to the Printf
function as f.Printf
rather than fmt.Printf
.
在程序中,我们现在将Printf
函数称为f.Printf
而不是fmt.Printf
。
While other languages favor aliasing a package for ease of use later in the program, Go does not. For instance, aliasing the fmt
package to f
would not be consistent with the style guide.
虽然其他语言更喜欢为程序包加上别名,以便于以后在程序中使用,但Go却没有。 例如,将fmt
包别名为f
将与样式指南不一致。
When renaming imports to avoid a name collision, you should aim to rename the most local or project specific import. For instance, if you had a local package called strings
, and you also needed to import the system package called strings
, you would favor renaming your local package over the system package. Whenever possible, it’s best to avoid name collision altogether.
在重命名导入以避免名称冲突时,您应旨在重命名最本地或特定于项目的导入。 例如,如果您有一个名为strings
的本地程序包,并且还需要导入一个名为strings
的系统程序包,则您将重命名本地程序包而不是系统程序包。 只要有可能,最好完全避免名称冲突。
In this section, we learned how we can alias an import to avoid colliding with another import in our program. It is important to remember that readability and clarity of your program is important, so you should only use aliasing to make the code more readable or when you need to avoid a naming collision.
在本节中,我们学习了如何为导入引入别名,以避免与程序中的另一个导入发生冲突。 重要的是要记住,程序的可读性和清晰度很重要,因此,应仅使用别名来使代码更具可读性,或者在需要避免命名冲突时使用。
格式化导入 (Formatting Imports)
By formatting imports, you can sort the packages into a specific order that will make your code more consistent. Additionally, this will prevent random commits from taking place when the only thing that changes is the sort order of the imports. Since formatting imports will prevent random commits, this will prevent unnecessary code churn and confusing code reviews.
通过格式化导入,您可以按特定顺序对软件包进行排序,这将使您的代码更加一致。 此外,当唯一改变的是导入的排序顺序时,这将防止发生随机提交。 由于格式化导入将防止随机提交,因此这将避免不必要的代码搅动和混乱的代码审查。
Most editors will format imports for you automatically, or will let you configure your editor to use goimports
. It is considered standard practice to use goimports
in your editor, as trying to manually maintain the sort order of your imports can be tedious and prone to errors. Additionally, if any style changes are made, goimports
will be updated to reflect those style changes. This ensures that you, and anyone that works on your code, will have consistent styling in your import blocks.
大多数编辑器会自动为您设置导入的格式,或者让您将编辑器配置为使用goimports
。 在您的编辑器中使用goimports
被认为是标准做法,因为尝试手动维护导入的排序顺序可能很乏味并且容易出错。 此外,如果进行了任何样式更改, goimports
将被更新以反映这些样式更改。 这样可以确保您以及任何处理您的代码的人在您的导入块中都具有一致的样式。
Here is what an example import block may look like before formatting:
这是格式化之前示例导入块的外观:
import (
"fmt"
"os"
"github.com/digital/ocean/godo"
"github.com/sammy/foo"
"math/rand"
"github.com/sammy/bar"
)
Running the goimport
tool (or with most editors that have it installed, saving the file will run it for you), you will now have the following format:
运行goimport
工具(或在大多数安装了它的编辑器中,保存文件将为您运行),您现在将具有以下格式:
import (
"fmt"
"math/rand"
"os"
"github.com/sammy/foo"
"github.com/sammy/bar"
"github.com/digital/ocean/godo"
)
Notice that it groups all standard library packages first and then groups third party packages together with blank lines. This makes is easier to read and understand what packages are being used.
请注意,它首先将所有标准库软件包分组,然后将第三方软件包和空白行分组在一起。 这样可以更容易阅读和理解正在使用的软件包。
In this section we learned that using goimports
will keep all of our import blocks properly formatted, and prevent unnecessary code churn between developers working on the same files.
在本节中,我们了解到使用goimports
将使我们的所有导入块保持正确的格式,并防止使用相同文件的开发人员之间不必要的代码搅动。
结论 (Conclusion)
When we import packages we’re able to call functions that are not built in to Go. Some packages are part of the standard library that installs with Go, and some we will install through go get
.
导入包时,我们可以调用Go内置的函数。 有些软件包是随Go一起安装的标准库的一部分,而有些则是通过go get
安装的。
Making use of packages allows us to make our programs more robust and powerful as we’re leveraging existing code. We can also create our own packages for ourselves and for other programmers to use in future programs.
利用包可以使我们在利用现有代码的同时使程序更强大,更强大。 我们还可以为自己和其他程序员创建自己的程序包 ,以供将来的程序使用。
翻译自: https://www.digitalocean.com/community/tutorials/importing-packages-in-go
golang导入包
上一篇: 关于使用C++对三个数进行排序