英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论