【发布时间】:2023-03-03 23:04:02
【问题描述】:
我是 Go 新手(来自 python),我在这里遇到了一些困难。我试图允许任何类型的切片进入我的结构/函数,它只包含该切片长度的计数。
import "go/types"
type Response struct {
Count int `json:"count"`
Results []types.Struct `json:"results`
}
func NewResponse(results []types.Struct) (r *Response) {
r.Count = len(results)
r.Results = results
return
}
【问题讨论】:
-
如何使用
json.RawMessage作为每个结果的类型,因为您似乎事先并不知道结果的 JSON 结构。例如。 play.golang.org/p/jEx4UgBnLP. -
Package go/types 不能用于这样的东西。重新设计你的解决方案:所有这些“任何类型”的想法在 Go 中都不能很好地工作。重新设计。那行得通。
标签: struct go types arguments slice