Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In golang, struct with a slice variable of any type is possible?

Tags:

go

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.

like image 256
tompal18 Avatar asked Oct 24 '25 19:10

tompal18


1 Answers

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

var s = []interface{}{1, 2, "three", SomeFunction}
fmt.Printf("Hello, %#v \n", 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.

like image 87
Eugene Lisitsky Avatar answered Oct 26 '25 09:10

Eugene Lisitsky