Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncomparable type error when []string field used (Go lang)

Tags:

go

I have a particular Go lang struct object that I'm interacting with and I expect it to be equal to itself. I'm passing the function to a function that simply returns it but that does it by accepting interface{} inputs/outputs

type Animal struct {
    name string
    food interface{}
}

type YummyFood {
    calories int
}

func echo_back(input interface{}) interface{} {
    return input
}

func main() {
    var tiger_food = Food{calories: 1000}
    var tiger = Animal{name: "Larry", food: tiger_food}
    output_tiger := echo_back(tiger)

    fmt.Printf("%T, %+v\n", tiger, tiger)
    fmt.Printf("%T, %+v\n", output_tiger, output_tiger)
    fmt.Println(tiger == output_tiger)
    fmt.Println(tiger == output_tiger.(Animal))

}

Running this, you see that the tiger and output_tiger appear to be the same and evaluate to be equal. Great. That's what I would expect. NOW, try using this definition for YummyFood

type YummyFood {
    calories int
    ingredients []string
}

All of a sudden, the output from echo_back does NOT evaluate to be the same as the input, even with the type assertion. I get 'panic: runtime error: comparing uncomparable type YummyFood'

The question is why does the addition of the []string type cause the input and output to be uncomparable? How can I modify output_tiger to get back the same thing I put in (i.e I expect it to be the same as 'tiger'). How do I reflect output_tiger to make it equal to tiger?

like image 990
dgh Avatar asked Apr 09 '13 04:04

dgh


1 Answers

It won't be fast, but you can use reflect.DeepEqual() to compare the slices (or just YummyFood). It does the work to loop through it to compare all the elements. You could probably make a more efficient function to do it, but if the one that's there is fast enough you'll save yourself some work and maybe some bugs. :-)

like image 153
Ask Bjørn Hansen Avatar answered Oct 16 '22 14:10

Ask Bjørn Hansen