英文:
GO Generic type of array in function parameter
问题
我有这个函数:
func functionX(collection []*interface{}) {
...
response, err := json.MarshalIndent(collection, "", " ")
...
}
我希望collection参数允许任何类型的数组,所以我尝试使用*interface{},但是我收到了这样的错误:
cannot use MyDataType (type []*model.MyDataType) as type []*interface {} in argument to middleware.functionX
英文:
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
答案1
得分: 5
你不能用那种方式做,但是你可以很容易地这样做:
func functionX(collection interface{}) error {
...
response, err := json.MarshalIndent(collection, "", " ")
...
}
英文:
You can't do it that way, however you can easily do this:
func functionX(collection interface{}) error {
...
response, err := json.MarshalIndent(collection, "", " ")
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论