在函数参数中使用的数组的通用类型

huangapple go评论80阅读模式
英文:

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, "", "  ")
    ...
}

playground

英文:

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

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

<kbd>playground</kbd>

huangapple
  • 本文由 发表于 2015年8月21日 03:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/32127246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定