go-redis / cache

Cache library with Redis backend for Golang
https://redis.uptrace.dev/guide/go-redis-cache.html
BSD 2-Clause "Simplified" License
757 stars 95 forks source link

Nil comparaison used for Item.Value field is not accurate #78

Open nabiltntn opened 2 years ago

nabiltntn commented 2 years ago

Hi,

I think the nil comparaison for cache.Item.Value field used in my places in the package is not correct :

https://github.com/go-redis/cache/blob/6382f515292d118aa7ceaf59599d665b3ebc8827/cache.go#L263

Here is an example a reproduction with nil comparaison :

// Item ( like cache.Item)
type Item struct {
    Name  string
    Value interface{}
}

// SampleStruct as value for Value
type SampleValue struct {
    port string
    host string
}

func main() {
    var sampleValue *SampleValue
    item := &Item{Name: "item1", Value: sampleValue}
    fmt.Println(item.Value == nil) // this is like the nil comparaison used in the package which return wrong result
}

A fix could be to use this sample isNil function :

func isNilFixed(i interface{}) bool {
    if i == nil {
        return true
    }
    switch reflect.TypeOf(i).Kind() {
    case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
        //use of IsNil method
        return reflect.ValueOf(i).IsNil()
    }
    return false
}
nabiltntn commented 2 years ago

An article about interface{} Nil comparaison and how to deal with it : https://mangatmodi.medium.com/go-check-nil-interface-the-right-way-d142776edef1