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

slier
  • 6,511
  • 6
  • 36
  • 55
nos
  • 19,875
  • 27
  • 98
  • 134
  • 3
    See the [FAQ](https://golang.org/doc/faq#convert_slice_of_interface). Possible dup: http://stackoverflow.com/questions/12990338/cannot-convert-string-to-interface – Charlie Tumahai Dec 11 '16 at 02:22

1 Answers1

3

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]}
}
Omar
  • 1,329
  • 11
  • 9