

Go Switch
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.
Switch statements express conditionals across many branches.
Syntax of Go Switch
switch expression {
case x:
// code block
case y:
// code block
case z:
...
default:
// code block
}
Example of Go Switch
package main
import (
"fmt"
"time"
)
func main() {
i := 2
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
}
Output
two
Example of Go Switch With default
package main
import (
"fmt"
"time"
)
func main() {
i := 4
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
default:
fmt.Println("Not available")
}
}
Output
Not available
Conclusion
In this page (written and validated by A. Gawali) you learned about Go Switch . What's Next? If you are interested in completing Go tutorial, your next topic will be learning about: Go Loops.
Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.
Share On: |
Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.