1. panic: runtime error: index out of range
含义:尝试访问切片(slice)或数组(array)中不存在的索引位置。例如,定义了一个长度为5的数组,却尝试访问索引为10的元素。
解决方法:检查代码中所有对切片/数组的索引操作,确保索引值大于等于0且小于切片/数组的长度(index >= 0 && index < len(slice))。
2. fatal error: concurrent map reads and map writes
含义:Go语言的原生map类型不是并发安全的,当多个goroutine同时读写同一个map时触发此错误。
解决方法:使用sync.Mutex或sync.RWMutex对map的访问进行同步(如读写操作前加锁),或改用sync.Map(适用于高并发场景)。
3. open /path/to/file: no such file or directory
含义:程序尝试打开的文件路径不存在,或文件未创建。
解决方法:使用os.Stat检查文件是否存在(如if _, err := os.Stat("/path/to/file"); os.IsNotExist(err) { ... }),确认文件路径正确且具备访问权限。
4. dial tcp: lookup example.com: no such host 或 dial tcp: connection refused
含义:前者表示DNS解析失败(无法将域名转换为IP地址);后者表示无法连接到目标服务器(服务器未运行、端口未开放或网络不通)。
解决方法:检查DNS设置(如/etc/resolv.conf)、网络连接(如ping example.com),确保目标服务器处于运行状态并监听正确端口。
5. http: panic serving [::]:8080: runtime error: invalid memory address or nil pointer dereference
含义:尝试解引用一个未初始化(值为nil)的指针,导致程序崩溃。常见于未赋值的指针变量或接口变量。
解决方法:在使用指针前进行nil判断(如if ptr != nil { *ptr = 1 }),确保指针已指向有效内存地址。
6. context deadline exceeded
含义:操作超过了context.WithTimeout或context.WithDeadline设置的超时时间,导致操作被取消。常见于HTTP请求、数据库查询等耗时操作。
解决方法:调整超时时间(如context.WithTimeout(context.Background(), 10*time.Second)),优化操作性能(如减少数据库查询次数),或处理超时错误(如重试机制)。
7. permission denied
含义:程序没有足够的权限执行操作,如读取受保护文件、绑定低端口(<1024)或写入系统目录。
解决方法:检查文件/目录的权限(如ls -l /path/to/file),使用chmod或chown修改权限(如chmod 644 file.txt),或以更高权限运行程序(如sudo,但需谨慎)。
8. goroutine leak
含义:创建的goroutine未正确退出(如未调用defer wg.Done()或channel未关闭),导致goroutine持续运行并占用系统资源。
解决方法:使用sync.WaitGroup等待所有goroutine结束(如wg.Add(1)在启动前、wg.Done()在退出前、wg.Wait()在主goroutine中),或通过channel通知goroutine退出(如close(doneChan))。
9. type assertion failed: interface conversion: interface {} is string, not int
含义:类型断言失败,即尝试将接口类型的值转换为不匹配的具体类型。例如,接口中存储的是string类型,却尝试断言为int类型。
解决方法:使用安全类型断言(带ok返回值),如val, ok := interfaceVar.(int); if !ok { ... },避免程序因断言失败而崩溃。
10. import cycle not allowed
含义:代码中存在循环依赖,即包A导入包B,包B又导入包A,导致编译错误。
解决方法:重构代码结构,消除循环依赖(如将公共逻辑提取到第三个包,或使用接口解耦)。