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包以这种方式生成随机数:

random.go
random.go
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 from 0 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值