Trying to use a map with interfaces but can can some explain type issue

I have this little program.
https://github.com/baldr9/sandbox/blob/main/learning/go/animals_v2.go

I don’t understand why I can’t call my function:
DisplayQueryResult(animals[arg1], arg1, arg2)

I get the error:
go build animals_v2.go

command-line-arguments

./animals_v2.go:221:31: cannot use animals[arg1] (type interface {}) as type Animal in argument to DisplayQueryResult:
interface {} does not implement Animal (missing Eat method)

However, all the types in the map satisfy the interface and I’m passing the value in the map to a function that accepts the interface.

I’m a noob to golang

Welcome to forum, could you provide a correct link (I’m getting 404).
I suppose, that animals is map[Animal]interface{}?
if so, you need to convert animals[arg1] to type Animal, because your function doesn’t know what interface{} is (it can be whatever you want). You need type assertion:
DisplayQueryResult(animals[arg1].(Animal), arg1, arg2)
look at this example: https://tour.golang.org/methods/15

2 Likes

Thanks, that worked

I am using map[Animal]interface{}
Converting to type Animal worked

DisplayQueryResult(animals[arg1].(Animal), arg1, arg2)

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.