Reference · Go Basics
TypeScript → Go
不要把 Go 当成陌生世界。先复用你已经掌握的函数、类型、条件和测试概念,再适应它不同的书写方式与工具链。
函数签名
// TypeScript
function readingTime(wordCount: number): number { ... }
// Go:名称在前,类型在后
func readingTime(wordCount int) int { ... }
变量与常量
const wordsPerMinute = 200 // 编译器推断为整数
var minutes int // 显式声明,零值是 0
minutes := wordCount / 200 // 函数内部短声明并推断类型
条件与运算
if wordCount <= 0 {
return 0
}
remainder := wordCount % wordsPerMinute
Go 的 if 条件不写圆括号,但代码块必须有花括号。两个整数相除仍得到整数,小数部分会被截断。
文件角色
go.mod:声明模块与 Go 版本main.go:普通 Go 源码;package main 加 func main() 可构建为程序*_test.go:只在 go test 时编译的测试文件本课程使用 Go 1.26.5 与 Modules。GOPATH 仍可能出现在环境变量和模块缓存路径中,但不再作为项目必须存放的工作目录来学习。
最短反馈循环
gofmt -w .
go test -v
go run .