在Go语言中,可以使用枚举和iota来实现基于类型的切换。

huangapple go评论84阅读模式
英文:

switch over enum / iota based type in golang

问题

我定义了一个枚举和结构体类型,如下所示:

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

type AreaNode struct {
    Location Coord2D
    Type NodeType
}

现在我正在遍历一系列具有不同类型的节点:

if node, ok := area.Nodes[coord]; ok {
    switch node.Type {
        case City:
            // 对于城市执行某些操作
        case Town:
            // 对于城镇执行某些操作
        case Village:
            // 对于村庄执行某些操作
    }
}

然而,我遇到了一个错误:二进制表达式中的类型不兼容。

你可以如何解决这个问题?

英文:

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

得分: 16

你可以使用两种方式来使用switch语句,一种是不带值,而是在每个case中放置比较表达式;另一种是将每个case视为对被检查值的==比较。例如:

if node, ok := area.Nodes[coord]; ok {
    switch node.Type {
        case City:
            // 对于城市执行某些操作
        case Town:
            // 对于城镇执行某些操作
        case Outpost:
            // 对于前哨站执行某些操作
    }
}

另一种switch语法用于在不基于单个值的条件之间进行切换。例如:

switch {
    case node.Type == City:
        // 对于城市执行某些操作
    case node.OtherParam == "foo":
        // ...
}

这基本上意味着你在二进制条件之间进行切换。个人而言,我只是用它来简化不依赖于单个值的长的if/else代码块,但我很少使用它。

英文:

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.

huangapple
  • 本文由 发表于 2015年6月27日 01:52:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/31079291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定