{"id":2097,"date":"2020-05-03T16:54:28","date_gmt":"2020-05-03T16:54:28","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=2097"},"modified":"2020-11-25T00:55:54","modified_gmt":"2020-11-24T19:25:54","slug":"switch-statement-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/switch-statement-golang\/","title":{"rendered":"Switch Statement in Go (Golang)"},"content":{"rendered":"\n

This is the\u00a0 chapter 13 of the golang comprehensive tutorial series. Refer to this link for other chapters of the series \u2013\u00a0Golang Comprehensive Tutorial Series<\/a><\/p>\n\n\n\n

Next Tutorial<\/strong> \u2013 Defer keyword<\/a>
Previous Tutorial<\/strong> \u2013
If Else<\/a>

Now let\u2019s check out the current tutorial. Below is the table of contents for current tutorial.<\/p>\n\n\n\n

Overview<\/strong><\/h1>\n\n\n\n

Switch statement are a perfect way to prevent a if-else ladder. Here is the format for switch statement<\/p>\n\n\n\n

switch statement; expression {\ncase expression1:\n     \/\/Dosomething\ncase expression2:\n     \/\/Dosomething\ndefault:\n     \/\/Dosomething\n}<\/code><\/pre>\n\n\n\n

This is how switch works. Give a switch expression<\/strong>, it goes through all cases and tries to find the first case expression<\/strong> that matches the switch expression<\/strong> otherwise the default case is executed if present. The order of matching is from top to bottom and then left to right (when the case contains multiple expressions as we will see later in this tutorial).<\/p>\n\n\n\n

Important Points<\/strong><\/h1>\n\n\n\n

Some important things to know about switch before we move to code examples<\/p>\n\n\n\n