doucaigai7176 2017-12-21 16:43
浏览 112

在Golang中为开关内的类型实现逻辑或

I have a []interface{} I am iterating over, and checking the type of each element within a switch. I would like to add a 'catch-all' case for any of several numeric types, i.e. int || float32 || float64.

It seems we are able to check whether an element is of a single distinct type, but I have not been able to figure out the syntax for checking multiple types with || (or).

Is this possible? What I've tried (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
", thing, t)


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

}
  • 写回答

2条回答 默认 最新

  • douzhuochao4027 2017-12-21 16:46
    关注

    Well, I thought you couldn't, until I read the spec. You can, and it works just like multiple cases in any other switch in Go:

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度