DEV Community

Cover image for Quick Tip: Use commas in cases of a switch in Go to match multiple conditions
Josh Ellis
Josh Ellis

Posted on

Quick Tip: Use commas in cases of a switch in Go to match multiple conditions

For Advent of Code day 12, the challenge included moving the position of a waypoint in certain directions. While writing the code, I discovered that I could match multiple conditions in a switch statement by using a comma to separate the values:

switch dir {
case 'N', 'S':
  waypoint.y += dist * dirMap[dir]
case 'W', 'E':
  waypoint.x += dist * dirMap[dir]
}
Enter fullscreen mode Exit fullscreen mode

In this case, if the direction (dir) is 'N' or 'S', it will match and execute the first block, and if it's 'W' or 'E', it will match the second.

I'm not sure if I'll ever have a need for this again (you could argue for a function or if/else chain here), but it's cool to know it exists!

Top comments (0)