现象

今天写接口写了这么个代码:

// 伪代码
func abc(id int64) ([]*model, error) {
key := "abc"
cache, err := Redis.Get(key).Bytes()
var res []*model
if err != nil {
res, err := service.GetFromDB(id)
if err != nil {
return res, err
}
Redis.Set(key, gostring.JsonEncode(res), 2*time.Minute)
} else {
json.Unmarshal(cache, &res)
}
return res, nil
}

然后本地测试接口,发现没有命中Redis时,res 总是 null,十分奇怪。

Test

仔细看看,你能知道是什么原因吗?


看到文章标题,应该能猜到吧!

我们写个test

package tests

import (
"errors"
"testing"
)

func TestVar(t *testing.T) {
var a int64
btn := true
if btn {
a, err := 2, errors.New("11")
t.Log("btn", a, err)
}

t.Log(a)
}

运行一下,

test

why?

结果看出来了吗?就是因为使用了 ##:=## 的缘故,变量在 if 内部才有效,不影响 if 外部变量,修改也就简单了:

...
res, err = service.GetFromDB(id)
...

去掉:即可。

这是使用go的:=需要注意的点,变量作用域需要注意哦!