0

I defined a struct

type container struct{ Data []interface{} } 

and was hoping to assign slice of all different kinds of data types to it. For example

ints := []int{2,3,4} tmp := container{ints} 

However, the compiler complains:

cannot use ints (type []int) as type []interface {} in field value

How should I define the container struct? Or the assignment needs to be done differently?

A complete example can be found here

1

1 Answer 1

6

The issue is that an array of structs can't be used as an array of interfaces, even if the individual structs implement the individual interfaces. You would need to append each element directly like so:

package main import ( "fmt" ) type a struct{ Data []interface{} } func main() { ints := []int{2,3,4} tmp := a{} for _, v := range ints { tmp.Data = append(tmp.Data, v) } fmt.Println(ints, tmp) // [2 3 4] {[2 3 4]} } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.