允许任何类型的切片作为参数

Allow a slice of any type into as argument

我是 Go 的新手(来自 python),我在这里遇到了一些困难。我正在尝试允许任何类型的切片进入我的 struct/func,它只包含该切片长度的计数。

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
}

您可以使用 interface{} 作为任何类型。

type Response struct {
  Count int `json:"count"`
  Results []interface{} `json:"results`
}

更新

len(rsp.results) 应该可以。 http://play.golang.org/p/RA2zVzWl2q

任意类型在 Go 中是完全合法的。在您的情况下,使用 []interface{} 作为 Results 的类型可能是合适的。当需要知道类型时,使用 type switch.

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`
}