cache icon indicating copy to clipboard operation
cache copied to clipboard

Nil comparaison used for Item.Value field is not accurate

Open nabiltntn opened this issue 3 years ago • 1 comments

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 avatar Dec 28 '21 01:12 nabiltntn

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

nabiltntn avatar Dec 28 '21 01:12 nabiltntn