go
它能做什么
本指南教你 Go 语言的最佳实践。内容包括如何处理错误,使用切片(slices)和映射(maps)等数据结构,以及如何借助协程(goroutine)和通道(channel)高效、清晰地管理并发任务。
适用场景
- ✓开始学习 Go 编程时。
- ✓审查或改进已有的 Go 代码时。
- ✓遇到常见的 Go 错误时。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/go/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“如何在 Go 中正确处理错误?”
每周 5 个新技能,1 分钟读完。
工作原理
本指南会对比“糟糕”和“良好”的代码示例,说明推荐的做法。它会解释为什么某种写法优于另一种,重点关注清晰度和效率。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Go: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for go.
Table of Contents
- Error Handling
- Slices & Maps
- Goroutines & Channels
- Structs & Interfaces
- Functions & Closures
- Anti-patterns specific to Go
1. Error Handling {#errors}
// ❌ Ignoring errors
result, _ := os.Open(path)
// ✅ — always handle; only use _ when error is provably irrelevant
result, err := os.Open(path)
if err != nil {
return fmt.Errorf("open %s: %w", path, err)
}
// ❌ Redundant error variable
err := doA()
if err != nil { return err }
err = doB()
if err != nil { return err }
// ✅ — each :=/: is fine; this is idiomatic Go. Don't try to "fix" it.
// What you CAN simplify: collapsing to one-liners where the if body is a single return
if err := doA(); err != nil { return err }
if err := doB(); err != nil { return err }
// ❌ Custom error type with no added value
type MyError struct{ msg string }
func (e MyError) Error() string { return e.msg }
// ✅ — use errors.New or fmt.Errorf unless callers need to inspect type
var ErrNotFound = errors.New("not found")
return fmt.Errorf("lookup %q: %w", key, ErrNotFound)
Wrap errors with %w (not %v) so callers can use errors.Is / errors.As.
2. Slices & Maps {#slices}
// ❌ Growing a slice without pre-allocation when size is known
var result []string
for _, item := range items {
result = append(result, item.Name)
}
// ✅
result := make([]string, 0, len(items))
for _, item := range items {
result = append(result, item.Name)
}
// ❌ Manual existence check before map write
if _, ok := m[key]; !ok {
m[key] = []string{}
}
m[key] = append(m[key], value)
// ✅ — append to nil slice is valid Go
m[key] = append(m[key], value)
// ❌ Copying a map by assignment (copies reference)
copy := original
// ✅
copy := make(map[K]V, len(original))
for k, v := range original { copy[k] = v }
3. Goroutines & Channels {#concurrency}
// ❌ Fire-and-forget goroutine with no lifecycle
go doWork()
// ✅ — use errgroup or WaitGroup to track completion
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
doWork()
}()
wg.Wait()
// ❌ Unbuffered channel causing unnecessary goroutine block
ch := make(chan Result)
go func() { ch <- compute() }()
result := <-ch
// ✅ — for single-result, buffered channel avoids goroutine leak if receiver exits early
ch := make(chan Result, 1)
go func() { ch <- compute() }()
result := <-ch
// ❌ select with a busy-wait default
for {
select {
case v := <-ch:
process(v)
default:
// spin
}
}
// ✅ — blocking select unless you genuinely need non-blocking
for v := range ch {
process(v)
}
Use golang.org/x/sync/errgroup for fan-out with error collection.
4. Structs & Interfaces {#structs}
// ❌ Large interface
type Storage interface {
Get(key string) ([]byte, error)
Set(key string, val []byte) error
Delete(key string) error
List(prefix string) ([]string, error)
// ... 10 more methods
}
// ✅ — small, composable interfaces
type Getter interface { Get(key string) ([]byte, error) }
type Setter interface { Set(key string, val []byte) error }
type Storage interface { Getter; Setter }
// ❌ Returning concrete struct from constructor (ties callers to implementation)
func NewStore() *RedisStore { ... }
// ✅ — return interface when you have or anticipate multiple implementations
func NewStore() Storage { return &RedisStore{...} }
// ❌ Pointer receiver for tiny value types
func (p *Point) X() float64 { return p.x }
// ✅ — value receiver for small immutable types
func (p Point) X() float64 { return p.x }
Rule: pointer receiver when method mutates state OR struct is large (>3 fields of non-trivial size). Value receiver otherwise.
5. Functions & Closures {#functions}
// ❌ Named return values used just to avoid a variable declaration
func divide(a, b float64) (result float64, err error) {
result = a / b
return
}
// ✅ — named returns are worth it only for deferred mutation or documentation
func divide(a, b float64) (float64, error) {
if b == 0 { return 0, errors.New("division by zero") }
return a / b, nil
}
…
常见问题
什么是 goroutine 和 channel?
它们是 Go 的并发工具。goroutine(协程)用于同时运行多个任务,channel(通道)则让这些任务之间能够安全地通信。
为什么要用 `%w` 来“包装”错误?
使用 `%w` 后,接收错误的代码就能借助 `errors.Is` 或 `errors.As` 等函数,检查该错误是否源自某个特定错误。
什么是“反模式”(anti-patterns)?
反模式是一些看似可行、但往往会让代码更难理解、效率更低或更容易出错的编程做法。本指南会告诉你如何在 Go 中避免它们。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5892
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。