【问题标题】:Allow a slice of any type into as argument允许任何类型的切片作为参数
【发布时间】: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


【解决方案1】:

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

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

更新

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

【讨论】:

  • 如果是接口,似乎无法调用len(results)
  • @electrometro:你可以使用反射来获取长度。
【解决方案2】:

任意类型在 Go 中是完全合法的。在您的情况下,使用[]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`
}

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 2012-05-23
    • 1970-01-01
    • 2020-08-29
    • 2017-01-18
    • 1970-01-01
    • 2014-09-18
    • 2020-08-05
    相关资源
    最近更新 更多