go安装
参考官网https://go.dev/learn/
配置环境变量 GOPATH D:\go_workspace
系统变量 %GOPATH%\src %GOPATH%\bin
go初始化项目
1、 创建一个模块
go mod init myProject/hello
如果报错:go: modules disabled by GO111MODULE=off; see ‘go help modules’
解决:go env -w GO111MODULE=on
原因是:当前使用的 Go 版本已经支持 Go Modules,但是你的代码中的 go111module 指令设置为 off,这意味着 Go Modules 功能被禁用了。
Go Modules 是 Go 语言提供的一种依赖管理机制,它可以帮助开发者管理包依赖关系,并提供了一种简单的方法来安装和更新包。go help modules可以查看modules帮助文档。
2、代码中引入包,下载依赖模块
如果报错:no required module provides package rsc.io/quote; to add it: go get rsc.io/quote
解决: go mod tidy
go: finding module for package rsc.io/quote
go: found rsc.io/quote in rsc.io/quote v1.5.2
3、调用另一个模块的方法
每一个模块中都有一个go.mod文件, 文件中有模块的名称,示例第一行:module example.com/greetings
另一个模块引用是,代码中import模块,用下面的命令适配查找:
go mod edit -replace example.com/greetings=…/greetings
go mod tidy
然后查看go.mod文件:
module example.com/hello
go 1.19
replace example.com/greetings => …/greetings
require example.com/greetings v0.0.0-00010101000000-000000000000
4、处理返回错误
内置errors模块
import "errors"
func Helllo(name string) (string, error) {
if name == "" {
return "", errors.New("empty name")
}
message := fmt.Sprintf("Hi, %v.", name)
return message, nil
}
5、打印log
内置log模块
import "log"
log.SetPrefix("xxx: ")
log.SetFlags(0)
log.Fatal(err) # 打印到控制台,并且退出程序
go测试方法
官方demo: https://go.dev/doc/tutorial/add-a-test
内置模块 testing
模块中创建test文件:xxx_test.go
测试名称格式: TestName,Name表示有关特定测试的信息
测试函数将指向测试包的测试.T类型的指针作为参数。您可以使用此参数的方法从测试中报告和日志记录。
运行测试:
go test
PASS
ok example.com/greetings 0.364s
go test -v -v表示获得列出所有测试及其结果的详细输出
=== RUN TestHelloName
— PASS: TestHelloName (0.00s)
=== RUN TestHelloEmpty
— PASS: TestHelloEmpty (0.00s)
PASS
ok example.com/greetings 0.372s