The Wayback Machine - https://web.archive.org/web/20240927193035/https://www.geeksforgeeks.org/switch-statement-in-go/
Open In App

Switch Statement in Go

Last Updated : 22 Jul, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value(also called case) of the expression. Go language supports two types of switch statements:

  1. Expression Switch
  2. Type Switch

Expression Switch

Expression switch is similar to switch statement in C, C++, Java language. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.

Syntax:

switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
...
default: Statement..
}

Important Points:

  • Both optstatement and optexpression in the expression switch are optional statements.
  • If both optstatementand optexpression are present, then a semi-colon(;) is required in between them.
  • If the switch does not contain any expression, then the compiler assume that the expression is true.
  • The optional statement, i.e, optstatement contains simple statements like variable declarations, increment or assignment statements, or function calls, etc.
  • If a variable present in the optional statement, then the scope of the variable is limited to that switch statement.
  • In switch statement, the case and default statement does not contain any break statement. But you are allowed to use break and fallthrough statement if your program required.
  • The default statement is optional in switch statement.
  • If a case can contain multiple values and these values are separated by comma(,).
  • If a case does not contain any expression, then the compiler assume that te expression is true.

Example 1:




// Go program to illustrate the 
// concept of Expression switch
// statement
package main
  
import "fmt"
  
func main() {
      
    // Switch statement with both 
    // optional statement, i.e, day:=4
    // and expression, i.e, day
    switch day:=4; day{
       case 1:
       fmt.Println("Monday")
       case 2:
       fmt.Println("Tuesday")
       case 3:
       fmt.Println("Wednesday")
       case 4:
       fmt.Println("Thursday")
       case 5:
       fmt.Println("Friday")
       case 6:
       fmt.Println("Saturday")
       case 7:
       fmt.Println("Sunday")
       default: 
       fmt.Println("Invalid")
   }
     
}


Output:

Thursday

Example 2:




// Go program to illustrate the 
// concept of Expression switch
// statement
package main
  
import "fmt"
  
func main() {
    var value int = 2
      
    // Switch statement without an     
    // optional statement and 
    // expression
   switch {
       case value == 1:
       fmt.Println("Hello")
       case value == 2:
       fmt.Println("Bonjour")
       case value == 3:
       fmt.Println("Namstay")
       default: 
       fmt.Println("Invalid")
   }
  
}


Output:

Bonjour

Example 3:




// Go program to illustrate the 
// concept of Expression switch
// statement
package main
  
import "fmt"
  
func main() {
    var value string = "five"
      
    // Switch statement without default statement
    // Multiple values in case statement
   switch value {
       case "one":
       fmt.Println("C#")
       case "two", "three":
       fmt.Println("Go")
       case "four", "five", "six":
       fmt.Println("Java")
   }  
}


Output:

Java

Type Switch

Type switch is used when you want to compare types. In this switch, the case contains the type which is going to compare with the type present in the switch expression.

Syntax:

switch optstatement; typeswitchexpression{
case typelist 1: Statement..
case typelist 2: Statement..
...
default: Statement..
}

Important Points:

  • The optional statement, i.e., optstatement is similar as in the switch expression.
  • If a case can contain multiple values and these values are separated by comma(,).
  • In type switch statement, the case and default statement do not contain any break statement. But you are allowed to use break and fallthrough statement if your program required.
  • The default statement is optional in type switch statement.
  • The typeswitchexpression is an expression whose result is a type.
  • If an expression is assigned in typeswitchexpression using := operator, then the type of that variable depends upon the type present in case clause. If the case clause contains two or more types, then the type of the variable is the type in which it is created in typeswitchexpression.

Example:




// Go program to illustrate the 
// concept of Type switch
// statement
package main
  
import "fmt"
  
func main() {
    var value interface{}
    switch q:= value.(type) {
       case bool:
       fmt.Println("value is of boolean type")
       case float64:
       fmt.Println("value is of float64 type")
       case int:
       fmt.Println("value is of int type")
       default:
       fmt.Printf("value is of type: %T", q)
         
   }
}


Output:

value is of type: <nil>


Previous Article
Next Article

Similar Reads

Golang Program to Show the Duplicate Case Error in Switch Statement
A switch's case must have a unique value. When repeated value is checked against the entire switch. The "duplicate case" error is arised. Let us discuss duplicate case error with the help of the examples: Example 1: C/C++ Code // Golang program that causes // duplicate case error package main import "fmt" // Main function func main() { va
1 min read
Golang Program that switch on floating-point numbers
With the help of switch case we can implement the functionality of as many if statements. In Golang, switch cases can work with strings, list of variables including integer values as well as floating values. Syntax: switch optstatement; optexpression{ case expression1: Statement.. case expression2: Statement.. ... default: Statement.. } Example 1:
2 min read
Golang program that uses switch, multiple value cases
Switch statement is a multiway branching which provides an alternative way too lengthy if-else comparisons. It selects a single block to be executed from a listing of multiple blocks on the basis of the value of an expression or state of a single variable. A switch statement using multiple value cases correspond to using more than one value in a si
3 min read
Switch Case with Break in For Loop in Golang
A switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value, also called the case of the expression. There can be various switch-case statements within a switch. Each case is followed by the value to be compared to. When the variable being switched on is e
3 min read
Golang Program that uses String Switch
With the help of switch case we can implement the functionality of as many if statements. In Golang, switch cases can work with strings, list of variables including integer values as well as floating values. Syntax: switch optstatement; optexpression{case expression1: Statement..case expression2: Statement..â€Ķdefault: Statement..}Example 1: In this
2 min read
Select Statement in Go Language
In Go language, the select statement is just like switch statement, but in the select statement, case statement refers to communication, i.e. sent or receive operation on the channel. Syntax: select{ case SendOrReceive1: // Statement case SendOrReceive2: // Statement case SendOrReceive3: // Statement ....... default: // Statement Important points:
4 min read
Golang | Deadlock and Default Case in Select Statement
In Go language, the select statement is just like a switch statement, but in the select statement, the case statement refers to communication, i.e. sent or receive operation on the channel. Syntax: select{ case SendOrReceive1: // Statement case SendOrReceive2: // Statement case SendOrReceive3: // Statement ....... default: // Statement In this arti
3 min read
Golang
Golang is a procedural and statically typed programming language having the syntax similar to C programming language. Sometimes it is termed as Go Programming Language. It provides a rich standard library, garbage collection, and dynamic-typing capability. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launch
2 min read
Learn Free Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. Programming languages are an essential part of software development because they create a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, searc
9 min read
Top 10 Golang Project Ideas with Source Code in 2024
Golang, or Go, a programming language was created by Google. It's widely used for building different kinds of applications like websites and cloud services. The fastest way to master this language is by building projects related to it. This article introduces 10 beginner-friendly to medium-difficulty projects in Golang with reference links to sourc
8 min read
How to Sort Golang Map By Keys or Values?
Let's say we have a map and want to find a specific key-value pair but it can be located in any order, so to have the map in Golang in a particular order, we can sort the map by its keys or values. In this article, we will see how to sort a map in go lang by its keys or values.  Sort By KeysTo sort a map by keys, we need to first create a list of k
5 min read
Class and Object in Golang
Every human (excluding infants) can relate to encapsulation irrespective of his/her prior knowledge of encapsulation. Do you wonder why? Simple. Recollect all the times when you were sick, and the doctor prescribed all those monstrous capsules dosage for a couple of days until you were okay again! The evil capsule contains all mysterious elements w
6 min read
Top 5 Golang Frameworks in 2024
Golang (or Go) is an open-source compiled programming language that is used to build simple, systematic, and secure software. It was designed by Google in the year 2007 and has been readily adopted by developers all over the world due to its features like memory safety, structural typing, garbage collection, and similarity to C-language. Golang web
7 min read
How to Parse JSON in Golang?
Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Syntax: func Unmarshal(data []byte, v interface{}) error Unmarshal parses the JSON-encoded d
4 min read
Inheritance in GoLang
Inheritance means inheriting the properties of the superclass into the base class and is one of the most important concepts in Object-Oriented Programming. Since Golang does not support classes, so inheritance takes place through struct embedding. We cannot directly extend structs but rather use a concept called composition where the struct is used
3 min read
Time Formatting in Golang
Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time.Time object. Syntax: func (t Time) Format(layout string) string We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows. .time-formatting-i
2 min read
fmt.Sprintf() Function in Golang With Examples
In Go language, fmt package implements formatted I/O with functions analogous to C's printf() and scanf() function. The fmt.Sprintf() function in Go language formats according to a format specifier and returns the resulting string. Moreover, this function is defined under the fmt package. Here, you need to import the "fmt" package in order to use t
2 min read
How to iterate over an Array using for loop in Golang?
An array is a data structure of the collection of items of the similar type stored in contiguous locations. For performing operations on arrays, the need arises to iterate through it. A for loop is used to iterate over data structures in programming languages. It can be used here in the following ways: Example 1: // Golang program to iterate over /
2 min read
strings.Join() Function in Golang With Examples
strings.Join() Function in Golang concatenates all the elements present in the slice of string into a single string. This function is available in the string package. Syntax: func Join(s []string, sep string) string Here, s is the string from which we can concatenate elements and sep is the separator which is placed between the elements in the fina
1 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
strings.Replace() Function in Golang With Examples
strings.Replace() Function in Golang is used to return a copy of the given string with the first n non-overlapping instances of old replaced by new one. Syntax: func Replace(s, old, new string, n int) string Here, s is the original or given string, old is the string that you want to replace. new is the string which replaces the old, and n is the nu
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
Golang Tutorial - Learn Go Programming Language | Beginner to Advanced
This Golang tutorial provides you with all the insights into Go Language programming, Here we provide the basics, from how to install Golang to advanced concepts of Go programming with stable examples. So, if you are a professional and a beginner, this free Golang tutorial is the best place for your learning. Golang, or Go Programming Language, is
10 min read
How to Split a String in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go strings, you are allowed to split a string into a slice with the help of the following functions. These functions are def
5 min read
How to Trim a String in Golang?
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. You can trim a string in different ways using the following list of functions. All these functions are defined under strings pa
6 min read
Different ways to concatenate two strings in Golang
In Go language, the string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding. In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator. It is also known as a concatenation operator. E
4 min read
Goroutines - Concurrency in Golang
Go language provides a special feature known as a Goroutines. A Goroutine is a function or method that executes independently and simultaneously in connection with any other Goroutines in your program. In other words, every concurrently executing activity in the Go language is known as a Goroutines. You can consider a Goroutine like a lightweight t
4 min read
Anonymous function in Go Language
Go language provides a special feature known as an anonymous function. An anonymous function is a function which doesn't contain any name. It is useful when you want to create an inline function. In Go language, an anonymous function can form a closure. An anonymous function is also known as function literal. Syntax: func(parameter_list)(return_typ
2 min read
Data Types in Go
Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows: Basic type: Numbers, strings, and booleans come under this category.Aggregate type: Array and structs come under this category.Reference type: Pointers, slices, maps, functions, and channels come unde
7 min read
Loops in Go Language
Go language contains only a single loop that is for-loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. In Go language, this for loop can be used in the different forms and the forms are: 1. As simple for loop It is similar that we use in other programming languages like C,
5 min read