doucan9079 2016-08-03 15:39
浏览 75
已采纳

Golang类型开关:如何匹配通用切片/阵列/地图/通道?

How can I use a Go Type Switch to match a generic slice, array, map, or channel?

package main

import (
    "fmt"
    "reflect"
)

func WhatIsIt(x interface{}) {
    switch X := x.(type) {
        case bool:
            fmt.Printf("Type Switch says %#v is a boolean.
", X)
        case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
            fmt.Printf("Type Switch says %#v is an integer.
", X)
        case float32, float64, complex64, complex128:
            fmt.Printf("Type Switch says %#v is a floating-point.
", X)
        case string:
            fmt.Printf("Type Switch says %#v is a string.
", X)
        case []interface{}:
            fmt.Printf("TypeSwitch says %#v is a slice.
", X)
        case map[interface{}]interface{}:
            fmt.Printf("TypeSwitch says %#v is a map.
", X)
        case chan interface{}:
            fmt.Printf("TypeSwitch says %#v is a channel.
", X)
        default:
            switch reflect.TypeOf(x).Kind() {
                case reflect.Slice, reflect.Array, reflect.Map, reflect.Chan:
                    fmt.Printf("TypeSwitch was unable to identify this item.  Reflect says %#v is a slice, array, map, or channel.
", X)
                default:
                    fmt.Printf("Type handler not implemented: %#v
", X)
            }
    }
}

func main() {
    WhatIsIt(true)
    WhatIsIt(1)
    WhatIsIt(1.5)
    WhatIsIt("abc")
    WhatIsIt([]int{1,2,3})
    WhatIsIt(map[int]int{1:1, 2:2, 3:3})
    WhatIsIt(make(chan int))
}

Here is the output:

Type Switch says true is a boolean.
Type Switch says 1 is an integer.
Type Switch says 1.5 is a floating-point.
Type Switch says "abc" is a string.
TypeSwitch was unable to identify this item.  Reflect says []int{1, 2, 3} is a slice, array, map, or channel.
TypeSwitch was unable to identify this item.  Reflect says map[int]int{1:1, 2:2, 3:3} is a slice, array, map, or channel.
TypeSwitch was unable to identify this item.  Reflect says (chan int)(0x104320c0) is a slice, array, map, or channel.

As you can see from the output, the case []interface{} fails to match the slice that I send in. I need to resort to using the reflect package instead.

If I explicitly write case []int, then it works for my given example, but it's impossible to know all the input types ahead of time, so I need a more general solution. I want to avoid using the reflect package if the Type Switch is able to handle this.

Is there any way to use the Type Switch to determine if an object is a slice/array/map/chan/etc...?

  • 写回答

1条回答 默认 最新

  • drouie2014 2016-08-03 15:44
    关注

    Type switches work with specific types. If you cannot enumerate all of the types in the switch, then the only option is to use the reflect package.

    v := reflect.ValueOf(x)
    switch v.Kind() {
    case reflect.Bool:
        fmt.Printf("bool: %v
    ", v.Bool())
    case reflect.Int, reflect.Int8, reflect.Int32, reflect.Int64:
        fmt.Printf("int: %v
    ", v.Int())
    case reflect.Uint, reflect.Uint8, reflect.Uint32, reflect.Uint64:
        fmt.Printf("int: %v
    ", v.Uint())
    case reflect.Float32, reflect.Float64:
        fmt.Printf("float: %v
    ", v.Float())
    case reflect.String:
        fmt.Printf("string: %v
    ", v.String())
    case reflect.Slice:
        fmt.Printf("slice: len=%d, %v
    ", v.Len(), v.Interface())
    case reflect.Map:
        fmt.Printf("map: %v
    ", v.Interface())
    case reflect.Chan:
        fmt.Printf("chan %v
    ", v.Interface())
    default:
        fmt.Println(x)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀