Search code examples
goreflect

Reflect.Value issues


In trying to test this business func:

//IsInSlice works like Array.prototype.find in JavaScript, except it
// returns -1 if `value` is not found. (Also, Array.prototype.find takes
// function, and IsInSlice takes `value` and `list`)
func IsInSlice(value interface{}, list interface{}) int {
    slice := reflect.ValueOf(list)

    for i := 0; i < slice.Len(); i++ {
        if slice.Index(i) == value {
            return i
        }
    }
    return -1
}

I find that it fails my sanity tests:

func TestIsInSlice(t *testing.T) {
    digits := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    slice := digits[3:8] // returns {3,4,5,6,7}

    type args struct {
        value interface{}
        list  interface{}
    }
    tests := []struct {
        name string
        args args
        want int
    }{
        {
            name: "SanityTest",
            args: args{value: 3,
                list: []int{3, 4, 5, 6, 7},
            },
            want: 0,
        },
        {
            name: "ElementAtEnd",
            args: args{
                value: 5,
                list:  slice,
            },
            want: 3,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := IsInSlice(tt.args.value, tt.args.list); got != tt.want {
                t.Errorf("IsInSlice() = %v, want %v", got, tt.want)
            }
        })
    }

}

The person responsible for fixing these bugs has no idea what is causing the bug, let alone how to fix it, and neither do me or the senior dev. So, I attempted to isolate the problem to try to identify it.

What I thought it was

When I logged the bugs, I thought they were because somehow, the value was being compared to the reflect.Value returned by slice.Index(i). I tried

reflect.DeepEqual(slice.Index(i), value)

but that fails. The only way I could get passing test is to use Int() to extract the value and use

var i int64 = 3

instead of the literal 3, which is flaky af.

What is the issue and how do we fix it?


Solution

  • The Index() method returns a reflect.Value. Use that value's Interface() method to get its underlying value and compare to that:

    func IsInSlice(value interface{}, list interface{}) int {
        slice := reflect.ValueOf(list)
        for i := 0; i < slice.Len(); i++ {
            if slice.Index(i).Interface() == value {
                return i
            }
        }
        return -1
    }