Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch over enum / iota based type in golang

Tags:

go

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?

like image 814
user18007 Avatar asked Dec 15 '22 13:12

user18007


1 Answers

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.

like image 84
Not_a_Golfer Avatar answered Feb 01 '23 23:02

Not_a_Golfer