← 返回
内容创作
中文
Go
Write reliable Go code avoiding goroutine leaks, interface traps, and common concurrency bugs.
编写可靠的 Go 代码,避免 goroutine 泄漏、接口陷阱和常见并发 bug。
ivangdavila
内容创作
clawhub
v1.0.2 1 版本 99858 Key: 无需
#latest
概述
Quick Reference
| Topic | File |
|---|
| ------- | ------ |
| Concurrency patterns | concurrency.md |
| Interface and type system | interfaces.md |
| Slices, maps, strings | collections.md |
| Error handling patterns | errors.md |
Goroutine Leaks
- Goroutine blocked on channel with no sender = leak forever—always ensure channel closes or use context
- Unbuffered channel send blocks until receive—deadlock if receiver never comes
for range on channel loops forever until channel closed—sender must close(ch)- Context cancellation doesn't stop goroutine automatically—must check
ctx.Done() in loop - Leaked goroutines accumulate memory and never garbage collect
Channel Traps
- Sending to nil channel blocks forever—receiving from nil also blocks forever
- Sending to closed channel panics—closing already closed channel panics
- Only sender should close channel—receiver closing causes sender panic
- Buffered channel full = send blocks—size buffer for expected load
select with multiple ready cases picks randomly—not first listed
Defer Traps
- Defer arguments evaluated immediately, not when deferred function runs—
defer log(time.Now()) captures now - Defer in loop accumulates—defers stack, run at function end not iteration end
- Defer runs even on panic—good for cleanup, but recover only in deferred function
- Named return values modifiable in defer—
defer func() { err = wrap(err) }() works - Defer order is LIFO—last defer runs first
Interface Traps
- Nil concrete value in interface is not nil interface—
var p *MyType; var i interface{} = p; i != nil is true - Type assertion on wrong type panics—use comma-ok:
v, ok := i.(Type) - Empty interface
any accepts anything but loses type safety—avoid when possible - Interface satisfaction is implicit—no compile error if method signature drifts
- Pointer receiver doesn't satisfy interface for value type—only
*T has the method
Error Handling
- Errors are values, not exceptions—always check returned error
err != nil after every call—unchecked errors are silent bugserrors.Is for wrapped errors—== doesn't work with fmt.Errorf("%w", err)- Sentinel errors should be
var ErrFoo = errors.New() not recreated - Panic for programmer errors only—return error for runtime failures
Slice Traps
- Slice is reference to array—modifying slice modifies original
- Append may or may not reallocate—never assume capacity
- Slicing doesn't copy—
a[1:3] shares memory with a - Nil slice and empty slice differ—
var s []int vs s := []int{} copy() copies min of lengths—doesn't extend destination
Map Traps
- Reading from nil map returns zero value—writing to nil map panics
- Map iteration order is random—don't rely on order
- Maps not safe for concurrent access—use
sync.Map or mutex - Taking address of map element forbidden—
&m[key] doesn't compile - Delete from map during iteration is safe—but add may cause issues
String Traps
- Strings are immutable byte slices—each modification creates new allocation
range over string iterates runes, not bytes—index jumps for multi-byte charslen(s) is bytes, not characters—use utf8.RuneCountInString()- String comparison is byte-wise—not Unicode normalized
- Substring shares memory with original—large string keeps memory alive
Struct and Memory
- Struct fields padded for alignment—field order affects memory size
- Zero value is valid—
var wg sync.WaitGroup works, no constructor needed - Copying struct with mutex copies unlocked mutex—always pass pointer
- Embedding is not inheritance—promoted methods can be shadowed
- Exported fields start uppercase—lowercase fields invisible outside package
Build Traps
go build caches aggressively—use -a flag to force rebuild- Unused imports fail compilation—use
_ import for side effects only init() runs before main, order by dependency—not file ordergo:embed paths relative to source file—not working directory- Cross-compile:
GOOS=linux GOARCH=amd64 go build—easy but test on target
版本历史
共 1 个版本
-
v1.0.2
当前
2026-03-28 22:37 安全 安全
安全检测
腾讯云安全 (Sanbu)
安全,无风险
查看报告
🔗 相关推荐
productivity
ivangdavila
创建、检查和编辑 Microsoft Word 文档及 DOCX 文件,支持样式、编号、修订记录、表格、分节符及兼容性检查等功能。
★ 438
📥 147,664
content-creation
fly0pants
广告情报与应用数据分析助手,支持搜索广告素材、分析应用排名、下载量、收入及市场洞察,用于广告素材和竞品分析。
★ 295
📥 136,493
content-creation
biostartechnology
消除AI写作痕迹,使文本更自然真实。基于维基百科"AI写作特征"指南,识别并修正夸张象征、宣传用语、肤浅-ing分析、模糊归因、破折号滥用、三项排比、AI词汇、负面平行结构及冗长连接词等模式。
★ 860
📥 199,867