Oriam
Oriam

Reputation: 641

GO Generic type of array in function parameter

I have this function:

func functionX(collection []*interface{}) {
    ...
    response, err := json.MarshalIndent(collection, "", "  ")
    ...
}

I want the collection parameter to allow arrays of any kind, that's why I tried with *interface{} but I'm receiving errors like this:

cannot use MyDataType (type []*model.MyDataType) as type []*interface {} in argument to middleware.functionX

Upvotes: 1

Views: 126

Answers (1)

OneOfOne
OneOfOne

Reputation: 99224

You can't do it that way, however you can easily do this:

func functionX(collection interface{}) error {
    ...
    response, err := json.MarshalIndent(collection, "", "  ")
    ...
}

playground

Upvotes: 5

Related Questions