Go 语言教程
Go 是什么、它为什么适合服务端、这套教程怎么学。
Key PointsGo 用极简语法 + 内置并发 + 单一可执行文件,换来部署和协作上的低摩擦。
Go 是什么
Go is an open-source language released by Google in 2009, with Ken Thompson and Rob Pike among its authors. Its goal was explicit: fix what made large C++/Java codebases slow to compile, hard to make concurrent and messy to manage dependencies.
Go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}Output
Hello, Go!它砍掉了什么
| Removed | Replaced by |
|---|---|
| 继承 | 组合 + 接口 |
| 异常 try/catch | 多返回值 error |
| 泛型(1.18 前) | 接口 + 代码生成;1.18 起有泛型 |
| 循环引用 | 编译期直接报错 |
| 未使用的变量 | 编译期直接报错 |
"Unused variables and imports fail the build" gets complaints, but it is deliberate: no dead code survives, and leftovers from a refactor surface immediately.
适合做什么
- API 服务、网关、微服务 —— 单文件部署,启动毫秒级
- CLI 工具 —— Docker、kubectl、Terraform、gh 都是 Go 写的
- 基础设施 —— etcd、Consul、Prometheus
- 桌面/前端 —— 生态弱,不推荐
学习路线
- 语法 —— 变量、类型、流程控制、函数
- 数据 —— 数组、切片、Map、结构体、指针
- 抽象 —— 接口、泛型、错误处理
- 并发 —— goroutine、channel、select
- 工程 —— 模块、测试、工具链
Examples are verified on Go 1.22+. Two 1.22 changes affect them: per-iteration loop variables, and
net/http route patterns like GET /users/{id}.Go 是什么
Go 是 Google 在 2009 年发布的开源语言,作者里有 Ken Thompson 和 Rob Pike。它的目标很明确:解决大型工程里 C++/Java 编译慢、并发难写、依赖管理混乱的问题。
Go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go!")
}Output
Hello, Go!它砍掉了什么
| 砍掉的 | 换成 |
|---|---|
| 继承 | 组合 + 接口 |
| 异常 try/catch | 多返回值 error |
| 泛型(1.18 前) | 接口 + 代码生成;1.18 起有泛型 |
| 循环引用 | 编译期直接报错 |
| 未使用的变量 | 编译期直接报错 |
「未使用的变量和 import 会编译失败」这一点常被抱怨,但它是刻意的:让代码库里不留死代码,也让重构时的残留立刻暴露。
适合做什么
- API 服务、网关、微服务 —— 单文件部署,启动毫秒级
- CLI 工具 —— Docker、kubectl、Terraform、gh 都是 Go 写的
- 基础设施 —— etcd、Consul、Prometheus
- 桌面/前端 —— 生态弱,不推荐
学习路线
- 语法 —— 变量、类型、流程控制、函数
- 数据 —— 数组、切片、Map、结构体、指针
- 抽象 —— 接口、泛型、错误处理
- 并发 —— goroutine、channel、select
- 工程 —— 模块、测试、工具链
本教程示例在 Go 1.22+ 上验证。1.22 改了两件事会影响示例:
for 循环变量每轮独立(不再共享同一个变量),以及 net/http 的路由支持 GET /users/{id} 写法。