dongpian6319 2019-02-27 18: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 18: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条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程