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
: