繁体   English   中英

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

[英]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可以将*json.RawMessage封送为[]byte类型

type Response struct {
    Count   int              `json:"count"`
    Results *json.RawMessage `json:"results`
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM