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

问题描述 投票:-2回答:2

我有一个[]interface{}我正在迭代,并检查开关内每个元素的类型。我想为几种数字类型中的任何一种添加“catch-all”案例,即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)
        }
    }

}
go types interface
2个回答
7
投票

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

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

3
投票

是的,这是可能的。但是t在任何化合物interface{}s或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
}
© www.soinside.com 2019 - 2024. All rights reserved.