dongpian6319 2019-02-27 10:05
浏览 43
已采纳

Slice接口上的Golang开关盒

Is it possible to differentiate between []interface{} and interface{} in a switch case?

Trying to create a decoding function in which you can pass in different types and then a switch case determines the type and then proceed to decode that particular type. Although I am having issues when the type passed is a []interface{}.

I have been experimenting with the reflect package but no luck thus far. See code snippet and playground link below.

package main

import (
    "fmt"
    "math/big"
)

type Test struct {
    t      interface{}
}

func main() {
    testVar1 := big.NewInt(0)
    testVar2 := int64(1)
    testVar3 := []byte("test")
    testVar4 := true
    testVar5 := []int{1, 2, 3, 4}
    var testVar6 Test

    Issue(testVar1)
    Issue(testVar2)
    Issue(testVar3)
    Issue(testVar4)
    Issue(testVar5)
    Issue(testVar6)
}

func Issue(t interface{}) {
    switch t.(type) {
    case *big.Int:
        fmt.Println("*big.Int")
    case int8, int16, int32, int64:
        fmt.Println("int8, int16, int32, int64")
    case []byte:
        fmt.Println("[]byte")
    case bool:
        fmt.Println("bool")
    case []interface{}:
        fmt.Println("how to get testVar5 to print here")
        fmt.Println("[]interface{}")
    case interface{}:
        fmt.Println("interface{}")
    default:
        fmt.Println("unsupported type")
    }
}

Results:

*big.Int
int8, int16, int32, int64
[]byte
bool
interface{}
interface{}

Is there any way to get testVar5 to hit the []interface{} case?

https://play.golang.org/p/U0dJF9CEbTX

展开全部

  • 写回答

2条回答 默认 最新

  • doushi7819 2019-02-27 10:57
    关注

    Is there any way to get testVar5 to hit the []interface{} case?

    No. See e.g. https://golang.org/doc/faq#convert_slice_of_interface

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部