[ SKILL_DOCUMENTATION ]
# Go 错误模式
常见的 Go 错误及其诊断与解决方案。
## 空指针错误
### panic: runtime error: invalid memory address or nil pointer dereference
go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation]
**原因**:
1. 在空指针上调用方法
2. 访问空结构体的字段
3. 解引用空指针
**解决方案**:
go
// 使用前检查 nil
if user != nil {
fmt.Println(user.Name)
}
// 遇到 nil 时提前返回
func processUser(user *User) error {
if user == nil {
return errors.New("user is nil")
}
// 继续处理
}
// 在适当的地方使用零值
type Config struct {
Timeout time.Duration
}
func (c *Config) GetTimeout() time.Duration {
if c == nil {
return 30 * time.Second // 默认值
}
return c.Timeout
}
---
## 切片/数组错误
### panic: runtime error: index out of range
go
panic: runtime error: index out of range [5] with length 3
**原因**:
1. 访问超出切片长度的索引
2. 访问空切片
3. 差一错误 (Off-by-one error)
**解决方案**:
go
// 先检查长度
if len(items) > index {
item := items[index]
}
// 安全获取第一个/最后一个元素
func first(items []string) (string, bool) {
if len(items) == 0 {
return "", false
}
return items[0], true
}
// 使用 range 进行迭代
for i, item := range items {
// 安全访问
}
---
### panic: runtime error: slice bounds out of range
go
panic: runtime error: slice bounds out of range [:5] with length 3
**解决方案**:
go
// 验证切片边界
func safeSlice(s []int, start, end int) []int {
if start len(s) {
end = len(s)
}
if start > end {
return nil
}
return s[start:end]
}
---
## Map 错误
### panic: assignment to entry in nil map
go
panic: assignment to entry in nil map
**原因**:
1. 写入未初始化的 map
2. map 已声明但未 make
**解决方案**:
go
// 错误
var m map[string]int
m["key"] = 1 // panic!
// 正确 - 使用 make
m := make(map[string]int)
m["key"] = 1
// 或者使用字面量初始化
m := map[string]int{}
m["key"] = 1
// 在结构体中,在构造函数中初始化
type Cache struct {
data map[string]string
}
func NewCache() *Cache {
return &Cache{
data: make(map[string]string),
}
}
---
### Map 访问返回零值
go
value := m["nonexistent"] // 返回