user2727195
user2727195

Reputation: 7330

Type assertion errors when casting from interface to actual object

Encountering type assertion errors in the example below.

Errors:

49: cannot convert z (type IZoo) to type Zoo: need type assertion

49: cannot assign to Zoo(z).animals

type IAnimal interface {}

type IZoo interface {}

type Zoo struct {
    animals map[string]IAnimal
}

func NewZoo() *Zoo {
    var z IZoo = &Zoo{}

    Zoo(z).animals = map[string]IAnimal{} // cannot convert z (type IZoo) to type Zoo: need type assertion
    
    return z // cannot use z (type IZoo) as type *Zoo in return argument: need type assertion
}

Upvotes: 0

Views: 854

Answers (1)

Zoyd
Zoyd

Reputation: 3559

The error message says it all: you need a type assertion.

y := z.(Zoo)
y.animals = map[string]IAnimal{}

Upvotes: 2

Related Questions