Произвольные типы полностью законны в Го. В вашем случае может быть целесообразно использовать []interface{}
как тип Results
. Когда все типы должны быть известны, используйте переключатель .
package main
import (
"fmt"
)
type Response struct {
Count int `json:"count"`
Results []interface{} `json:"results`
}
func NewResponse(results []interface{}) (r *Response) {
r.Count = len(results)
r.Results = results
return
}
func AssertResultType(results []interface{}) {
for _, v := range results {
switch v := v.(type) {
default:
fmt.Printf("unexpected type %T\n", v) //t has unexpected type
case bool:
fmt.Printf("boolean %t\n", v) // t has type bool
case int:
fmt.Printf("integer %d\n", v) // t has type int
case string:
fmt.Printf("string %q\n", v) // t has type string
}
}
}
func main() {
args := []interface{}{1, "hello", true, "foo", 21}
r := NewResponse(args)
AssertResultType(r.Results)
}
В случае JSON, *json.RawMessage
может быть маршалируются типа []byte
type Response struct {
Count int `json:"count"`
Results *json.RawMessage `json:"results`
}
Что об использовании 'json.RawMessage' как тип для каждого результата, так как вы, кажется, не знает JSON структура результатов перед фронтом. Например. http://play.golang.org/p/jEx4UgBnLP. –
Пакет go/types не может использоваться для таких вещей. Редизайн вашего решения: все эти идеи «любого типа» не очень хорошо работают в Go. Редизайн. Это работает. – Volker