0

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
}

1 Answer 1

2

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

y := z.(Zoo)
y.animals = map[string]IAnimal{}
Sign up to request clarification or add additional context in comments.

5 Comments

couldn't you do it in one line, do we need separate declaration and assignment
@user2727195 z.(Zoo).animals = what do you think this expression should do? What it does - it creates a temporary object that is to be thrown away after this statement. Hence, a question: what does it mean to assign a value to an object's field that you would not be able to access? You basically can remove that line and the observed behaviour of a program would not change.
@zerkms is there an explanation on the docs about this temporary object
I'm not sure. It's a generic knowledge - structs in Go copy on assignment.
to clarify, everything in Go is a copy on assignment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.