字
字节笔记本
2026年5月3日
effective-go - Go 语言最佳实践指南
API中转
¥120
Go 语言最佳实践指南,基于官方 Effective Go 文档,帮助开发者编写地道、高效的 Go 代码。
项目简介
effective-go 将 Go 语言官方的 Effective Go 指南集成到 AI 辅助编程中。当编写、审查或重构 Go 代码时,该 skill 会自动应用 Go 语言的惯用写法和最佳实践,确保代码质量。
核心功能
| 特性 | 说明 |
|---|---|
| 自动应用 | 编写/审查/重构 Go 代码时自动触发 |
| 代码格式化 | 强制使用 gofmt 统一格式 |
| 命名规范 | 混合大小写命名规范,无下划线 |
| 错误处理 | 总是检查错误,返回而非 panic |
| 并发模式 | 通过通信共享内存 (使用 channels) |
| 接口设计 | 保持接口小巧 (1-3 个方法最佳) |
| 文档规范 | 导出符号必须有文档注释 |
最佳实践要点
格式化
非协商规则: 总是使用
gofmt
bash
gofmt -w your_file.go
go fmt ./...命名规范
go
// ✓ 正确: 混合大小写,无下划线
type HTTPServer struct {}
func getUserData() {}
const MaxRetries = 3
// ✗ 错误: 使用下划线
type HTTP_Server struct {}
func get_user_data() {}错误处理
go
// ✓ 正确: 总是检查并返回错误
func processFile(path string) error {
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read file: %w", err)
}
return nil
}并发模式
go
// ✓ 正确: 通过通信共享内存
func worker(ch chan<- Result) {
result := process()
ch <- result
}
func main() {
ch := make(chan Result)
go worker(ch)
result := <-ch
}接口设计
go
// ✓ 正确: 接口保持小巧
type Reader interface {
Read(p []byte) (n int, err error)
}
// 接受接口,返回具体类型
func ProcessData(r Reader) []byte {
// 实现...
}命名速查
| 类型 | 规则 | 示例 |
|---|---|---|
| 常量 (导出) | MixedCaps | MaxRetries, DefaultTimeout |
| 变量 (未导出) | mixedCaps | userData, responseTime |
| 函数 (导出) | MixedCaps | GetUser, ProcessData |
| 接口 | 通常 -er 后缀 | Reader, Writer, Stringer |
参考资源
- Effective Go: https://go.dev/doc/effective_go
- Code Review Comments: https://github.com/golang/go/wiki/CodeReviewComments
- Go Proverbs: https://go-proverbs.github.io/
分享: