Go panic记录:SIGSEGV: segmentation violation

1,080 阅读1分钟

背景:使用redis缓存数据,get方法获取数据时出现此paic错误,且为“untime error: invalid memory address or nil pointer dereference”

解决问题的过程:

1.先定位到代码,由于是在本地开发,先开启ide断点调试,发现redis缓存池中pool字段为空

//CacheRedisPool 缓存池
type CacheRedisPool struct { 
  // ...
  pool *redis.Pool  // 此字段为nil
}

2.马上联想到可能redis没初始化,因为我之前是在另一个包写go test,在那里写了一个init方法

func init() {
    err := redis.InitRedisRepo()
    // ...
}

3.至此,问题解决!

总结:

1.写代码一定要养成良好的习惯,重要的初始化方法想办法提出来

2.不要被陌生的错误迷惑,99%的错误都是人为的!

3.在test文件中写初始化的方法可以放在TestMain中