在Golang中为switch中的类型实现逻辑OR

时间:2017-12-21 16:43:30

标签: go types interface

我有[]interface{}我正在迭代,并检查交换机中每个元素的类型。我想添加一个“全能”的产品。几种数字类型中的任何一种的情况,即int || float32 || float64

我们似乎能够检查一个元素是否属于单一的不同类型,但我无法找出使用||(或)来检查多个类型的语法。

这可能吗?我尝试过的事情(Playground):

package main

import (
    "fmt"
)

func main() {

    things := []interface{}{"foo", 12, 4.5, true}

    for _, thing := range things {

        switch t := thing.(type) {

        // How can we implement logical OR for types to implement a catch-all for numerics?
        // Throws error: "type <type> is not an expression"
        // case ( int || float64 ) :
        //  fmt.Printf("Thing %v is a 'numeric' type: %T\n", thing, t)


        // Single discrete types work fine, of course
        case string :
            fmt.Printf("Thing %v is of type: %T\n", thing, t)   
        case int :
            fmt.Printf("Thing %v is of type: %T\n", thing, t)
        case float64 :
            fmt.Printf("Thing %v is of type: %T\n", thing, t)
        case bool :
            fmt.Printf("Thing %v is of type: %T\n", thing, t)
        default :
            fmt.Printf("Thing %v is of unknown type\n", thing)
        }
    }

}

2 个答案:

答案 0 :(得分:7)

嗯,我认为你不可能,直到我read the spec。你可以,它就像Go中的任何其他switch中的多个案例一样工作:

case bool, string:
    printString("type is bool or string")  // type of i is type of x (interface{})

答案 1 :(得分:3)

是的,这是可能的。但是,t在任何复合interface{}case案例中都有default类型。

switch t := v.(type) {
case string:
    // t is of type string
case int, int64:
    // t is of type interface{}, and contains either an int or int64
default:
    // t is also of type interface{} here
}