在golang中,可以使用具有任何类型的slice变量的struct吗?

Simple golang app gives below error

.\test.go:13: cannot use ds (type Data_A) as type []interface {} in field value

for below code

package main

type Data_A struct {
    a string
}

type DTResponse struct {
    Data []interface{} `json:"data"`
}

func main() {
    ds := Data_A{"1"}
    dtResp := &DTResponse{ Data:ds}

    print(dtResp)
}

I would like to have a struct with slice variable of any type. Using struct{} gives the same error.

In Java I could use Object as it is the parent object of any object. But I could not find such one in golang.

Any help would be appreciated.

Yes, as a slice of interface{} which can hold any arbitrary value.

var s = []interface{}{1, 2, "three", SomeFunction}
fmt.Printf("Hello, %#v 
", s)

Output:

Hello, []interface {}{1, 2, "three", (func())(0xd4b60)} 

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

But I do not recommend simulate dynamic-typed languages (like Python, JavaScript, PHP, etc) this way. Better to use all static-typed benefits from Go, and leave this feature as a last resort, or as a container for user input. Just to receive it and convert to strict types.

Typing

Go is a strongly explicitly typed language thus you can't substitute an object of one type with another (it is already compiled in this way). Also when you do type Data_A struct {... you define new type named Data_A. []interface{} and Data_A are completely different types and these types (like any other) are not interchangeable. Note, even interface{} is not interchangeable with anything. You can pass any type in a function like this func f(a interface{}){... but inside the function you will have exactly interface{} type and you should assert it to use properly.

Fix#1

package main

type Data_A struct {
    a string
}

type DTResponse struct {
    Data Data_A `json:"data"`
}

func main() {
    ds := Data_A{"1"}
    dtResp := &DTResponse{ Data:ds}

    print(dtResp)
}

Fix#2

package main

type DTResponse struct {
    Data []interface{} `json:"data"`
}

func main() {
    ds := []interface{}{"1"}
    dtResp := &DTResponse{ Data:ds}

    print(dtResp)
}

Possibly the cause of confusion: struct is not slice or array.