user99999
user99999

Reputation: 2024

Appending concrete values to array of interfaces

I have the following structures:

type Type interface {
  getFoo() []byte
}

type Concrete struct {
}

func (this *Concrete) getFoo() []byte {
   example := []byte{2, 3, 4}
   return example
}

Now I have some array of Type interfaces, e.g.:

var arr []*Type

And I want to create array of concrete structures and initialize the above array with it, e.g.:

var cObjArr []*Concrete
cObj := new(Concrete)
cObjArr = append(cObjArr, cObj)
arr = cObj

But it gives me an error that cannot use type []*Concrete as type []*Type in assignment. What's wrong?

Upvotes: 1

Views: 476

Answers (2)

Andy Schweig
Andy Schweig

Reputation: 6739

First of all, you should declare arr as []Type instead of []*Type. The objects you want to put in the array are Type, not *Type (*Concrete implements the Type interface).

Based on the error, your code must be trying to do arr = cObjArr. You can't do that because the types of the two slice objects are different. Instead, you can append cObj directly to arr.

Upvotes: 0

sberry
sberry

Reputation: 132078

There are a few problems here.

First,

type Type interface{} {
  getFoo() []byte
}

should be

type Type interface {
  getFoo() []byte
}

I assume that is a result of trying to show a small, reproducible example.

The next is that arr should be a slice of type Type, not *Type. A pointer to an interface is VERY rarely what you actually mean.

So, your arr is now a slice of Type... []Type. For the remainder of the current scope arr will always HAVE TO BE of type []Type.

cObjArr is of type []*Concrete. That's fine, but the value of cObjArr can not be assigned to arr since it is a different type.

You have a couple options here.

  1. Instead of appending to cObjArr, just append to arr

https://play.golang.org/p/m3-83s6R5c

  1. Or iterate through cObjArr and append to arr

https://play.golang.org/p/wvWaChcOWY

Upvotes: 3

Related Questions