包和模块
在 Go 中,包名称需遵循约定。 包使用其导入路径的最后一部分作为名称。 例如,Go 标准库包含名为 math/cmplx 的包,该包提供用于处理复数的有用代码。 此包的导入路径为 math/cmplx,导入包的方式如下所示:
import "math/cmplx"
若要引用包中的对象,请使用包名称cmplx
,如下所示:
cmplx.Inf()
创建包
不同于其他编程语言,Go 不会提供 public 或 private 关键字,以指示是否可以从包的内外部调用变量或函数。 但 Go 须遵循以下两个简单规则:
- 如需将某些内容设为专用内容,请以小写字母开始。
- 如需将某些内容设为公共内容,请以大写字母开始。
接下来,让我们将以下代码添加到我们要创建的计算器包:
package calculator
var logMessage = "[LOG]"
// Version of the calculator
var Version = "1.0"
func internalSum(number int) int {
return number - 1
}
// Sum two integer numbers
func Sum(number1, number2 int) int {
return number1 + number2
}
创建模块
Go 模块通常包含可提供相关功能的包。 包的模块还指定了 Go 运行你组合在一起的代码所需的上下文。 此上下文信息包括编写代码时所用的 Go 版本。
此外,模块还有助于其他开发人员引用代码的特定版本,并更轻松地处理依赖项。 另一个优点是,我们的程序源代码无需严格存在于 $GOPATH/src 目录中。 如果释放该限制,则可以更方便地在其他项目中同时使用不同包版本。
因此,若要为calculator
包创建模块,请在根目录($GOPATH/src/calculator)
中运行以下命令:
go mod init github.com/myuser/calculator
运行后,目录如下
src/
calculator/
go.mod
sum.go
若要在其他程序中引用calculator
包,需要使用模块名称进行导入。 在这种情况下,其名称为github.com/myuser/calculator
。
引用本地包(模块)
树文件结构现应如下所示:
src/
calculator/
go.mod
sum.go
helloworld/
main.go
重写main.go文件,如下所示:
package main
import (
"fmt"
"github.com/myuser/calculator"
)
func main() {
total := calculator.Sum(3, 5)
fmt.Println(total)
fmt.Println("Version: ", calculator.Version)
}
如果立即尝试运行程序,它将不起任何作用。 你需要告诉 Go,你会使用模块来引用其他包。 为此,请在 $GOPATH/src/helloworld 目录中运行以下命令:
go mod init helloworld
在上一个命令中,helloworld 是项目的名称。 此命令会创建一个新的go.mod
文件,因此,树目录会如下所示:
src/
calculator/
go.mod
sum.go
helloworld/
go.mod
main.go
由于你引用的是该模块的本地副本,因此你需要通知 Go 不要使用远程位置。 因此,你需要手动修改 go.mod 文件,使其包含引用,如下所示:
module helloworld
go 1.14
require github.com/myuser/calculator v0.0.0
replace github.com/myuser/calculator => ../calculator
replace
关键字指定使用本地目录,而不是模块的远程位置。 在这种情况下,由于helloworld
和calculator
程序在$GOPATH/src
中,因此位置只能是 ../calculator