duanfei1975 2015-06-26 17:52
浏览 29
已采纳

在golang中切换基于枚举/基于iota的类型

I defined an enumeration and struct type like so:

type NodeType int
const (
        City NodeType = iota
        Town
        Village
)

type AreaNode struct {
        Location Coord2D
        Type NodeType
}

and now I'm iterating over a series of nodes that each have a type

if node, ok := area.Nodes[coord]; ok {
    switch node.Type {
        case node.Type == City:
            // do something for City
        case node.Type == Town:
            // do something for Town
        case node.Type == Outpost:
            // do something for Outpost
    }
}

However I'm getting an error: incompatible types in binary expression.

How can I resolve this?

  • 写回答

1条回答 默认 最新

  • dtueufe82643 2015-06-26 18:00
    关注

    you either do a switch with no value, and put comparison expressions in each case, or you treat each case as a == for the checked value. e.g.:

    if node, ok := area.Nodes[coord]; ok {
        switch node.Type {
            case  City:
                // do something for City
            case Town:
                // do something for Town
            case Outpost:
                // do something for Outpost
        }
    }
    

    The other switch syntax is used when you're switching between conditions that are not based on a single value. e.g.

    switch {
        case node.Type == City:
            // do something for City
        case node.OtherParam == "foo":
            ///
    }
    

    Which means basically you're switching between binary conditions. Personally, I use it just to remove clutter from long if/else blocks that don't rely on a single value, but I rarely use it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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