Go笔记(1)基础

组织架构调整之后,公司的后端由 python 变成了 go,作为一个全栈工程师,自然是需要了解一下这个语言,Go笔记是初级学习的第一阶段。
本篇包含基础、运行指令、编写测试程序、benchmark。IDE 插件相关。

基础知识

  1. Go 语言主要为了解决:多核硬件架构、超大规模分布式计算集群
    (上万+)、Web 模式导致的前所未有的开发规模和更新速度。
  2. 并发支持、垃圾回收机制。编译的静态类型语言,尽管有 GC,依然可以通过指针去访问内存。

学习路径

语法 –> 并发任务的实现 –> 常见架构模式(pipe-filter, micro-kernel)–> 性能优化 –> 高可用服务

指令

1
2
3
4
# 运行
go run ***.go
# 编译-独立的二进制文件(命令行./***即可运行),可通过容器部署
go build ***.go

代码结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main
import (
"fmt"
"os"
)

const ( // 快速设置连续值
Open = 1 << iota
Close
Pending
)

func main() { // main中无法传入参数
fmt.Println("Hello World")
os.Exit(0) // 返回
}

测试

单元测试

  1. 源码⽂件以 _test 结尾:xxx_test.go
  2. 测试⽅法名以 Test 开头:func TestXXX(t *testing.T) {…}
  3. 内置单元测试框架:Fail, Error:该测试失败,该测试继续,其他测试继续执行;FailNow, Fatal:该测试失败,该测试中止,其他测试继续执行
    1
    2
    # -v 打印 t.Log 内容
    go test -v -cover

benchmark

1
2
3
4
5
6
7
8
9
func BenchmarkConcatStringByAdd(b *testing.B) {
//与性能测试⽆关的代码
b.ResetTimer()
for i := 0; i < b.N; i++ {
//测试代码
}
b.StopTimer()
//与性能测试⽆关的代码
}

运行benchmark,-bench=<相关benchmark测试>

1
2
3
4
5
6
go test -bench=.
# 输出更多信息,分析性能原因
go test -bench=. -benchmem
# cpu 调优示例
go test -bench=. -cpuprofile=cpu.prof
go tool pprof cpu.prof

Atom 离线安装 go-plus 插件(适用于mac)

Atom 自带的 install packages 安装失败,查阅资料发现有离线安装教程。

1
2
3
4
cd ~/.atom/packages
git clone https://github.com/joefitzgerald/go-plus.git
cd go-plus
npm install

Q1:atom 保存时出现“go: cannot find main module, but found .git/config in /Users//go_learning
to create a module there, run:
cd ../../.. && go mod init”
实验:执行该语句没用,报错“go: cannot determine module path for source directory /Users/
/go_learning (outside GOPATH, module path must be specified)”
A1:出错原因:出错原因是开启了 go mod,但是没有初使化生成 go.mod 文件。GO111MODULE 是 Go 1.11 引入的新版模块管理方式,快速解决方式是将其设置为 auto(具体实现见笔记5)。

1
go env -w GO111MODULE=auto

Atom 中可以看到 GO111MODULE 已经变化,这种解决方式可能会影响其他。

Q2:go mod init 报错 go: cannot determine module path for source directory
A2:在GOPATH之外,必须指定模块路径

1
go mod init 文件夹名

Q3:t.Log打印不出内容了,只会显示运行时间?
A3:Atom中需要安装Go plus插件,然后在Preferences..->Packages. 找到对应的Installed Packages “go-plus”。Settings 把 Run Tests With Verbose Flag Set 勾选上

附录
VS Code安装go插件失败原因分析以及解决方案
VSCode安装go插件失败的解决方案
断⾔
Atom Vscode Go test测试无法显示t.Log的打印日志内容


Go笔记(1)基础
https://guoningyan.com/2024/02/20/Go笔记(1)基础/
作者
Ningyan Guo
发布于
2024年2月20日
许可协议