The switch statement in Golang

The switch statement is one of the most important control flow in programming. It improves on the if-else chain in some cases. Thus making it substantially easy to do the same task with much less code. In this post, we will see how we can use the switch statement in the Go programming language.

What is Golang Switch Statement?

The switch statement is a control flow mechanism by which a program can give control to different segments for different cases. It consists of the switch expression and the case blocks. Switches in Go can work with any type of variable as we will see.

The switch statement syntax

The syntax for the switch statement is relatively simple. We have to use the “switch” keyword to start the switch block then values and after that, the block can have multiple cases that will match the value. Below is the syntax for the switch-case.

The single-case switch statement

Switch-case in Go can have any number of case variables. Here is an example of a simple switch statement which only takes a single value to match. Later on, we will see that we can have as many as we want. So, here is the code for that.

The multi-case switch statement

In the case block, we can have multiple values. That means if any of the values match then the block executes. Here is an example showing a multi-case switch statement.

The “break” keyword

In the switch block, we can have the break keyword which will exit out of the entire block. The keyword has its own application. When we don’t want to run the case entirely we can simply use the break keyword. And that will allow us to exit from the block. Here is the break keyword in action.

The “fallthrough” keyword

Go has the fallthrough keyword which passes the execution to the next case. Now, sometimes we don’t want to go any further with the current case. We simply move on to the next one. The fallthrough keyword is just for that. The fallthrough keyword can be used as shown below.

The switch statement with the variable initializer

The switch statement in Go can declare the variable first then use it at the same time. This is an optional statement, which is pretty handy at times. Here is shown how to initialize the variable with the switch statement.

The switch statement with a predeclared variable

A variable declared before can be used in the switch statement as well. We can either check it at the time of the case declaration. Then we don’t need to put an expression after the switch keyword. Or, we can use that after the switch keyword and use it as a regular switch case. Examples of both are shown below.

The conditional case statement

Switches in Go can have conditions in the case. That means when the conditions match the block will execute. This is an example of using conditions in the cases.

The default case

The default case, as the name suggests is the block that will execute if none of the other values match. Here is an example using the default case.

Type-switches in Go

Go have type-switches , which allows using types instead of values in the switch statement. In the expression of the type-switch block, only interfaces can be used.

Golang Switch statement benefits

The switch statement can be used as a replacement for the if-else block. Sometimes it becomes verbose when we use the if-else block. At that point, the switch statement may be beneficial.

Go by Example : Switch

express conditionals across many branches.

main
( "fmt" "time" )
main() {

Here’s a basic .

:= 2 fmt.Print("Write ", i, " as ") switch i { case 1: fmt.Println("one") case 2: fmt.Println("two") case 3: fmt.Println("three") }

You can use commas to separate multiple expressions in the same statement. We use the optional case in this example as well.

time.Now().Weekday() { case time.Saturday, time.Sunday: fmt.Println("It's the weekend") default: fmt.Println("It's a weekday") }

without an expression is an alternate way to express if/else logic. Here we also show how the expressions can be non-constants.

:= time.Now() switch { case t.Hour() < 12: fmt.Println("It's before noon") default: fmt.Println("It's after noon") }

A type compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable will have the type corresponding to its clause.

:= func(i interface{}) { switch t := i.(type) { case bool: fmt.Println("I'm a bool") case int: fmt.Println("I'm an int") default: fmt.Printf("Don't know type %T\n", t) } } whatAmI(true) whatAmI(1) whatAmI("hey") }
go run switch.go Write 2 as two It's a weekday It's after noon I'm a bool I'm an int Don't know type string

Next example: Arrays .

by Mark McGranaghan and Eli Bendersky | source | license

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, go introduction.

  • Golang Getting Started
  • Go Variables
  • Go Data Types
  • Go Print Statement
  • Go Take Input
  • Go Comments
  • Go Operators
  • Go Type Casting

Go Flow Control

  • Go Boolean Expression
  • Go if...else
  • Go for Loop
  • Go while Loop
  • Go break and continue

Go Data Structures

Go Functions

  • Go Variable Scope
  • Go Recursion
  • Go Anonymous Function
  • Go Packages

Go Pointers & Interface

  • Go Pointers
  • Go Pointers and Functions
  • Go Pointers to Struct
  • Go Interface
  • Go Empty Interface
  • Go Type Assertions

Go Additional Topics

Go defer, panic, and recover

Go Tutorials

In Go, the switch statement allows us to execute one code block among many alternatives.

The expression after the switch keyword is evaluated. If the result of the expression is equal to

  • case 1 - code block 1 is executed
  • case 2 - code block 2 is executed
  • case 3 - code block 3 is executed

In case there is no match, the default code block is executed.

Note : We can also use if...else statements in place of switch . However, the syntax of the switch is much cleaner and easier to write.

Flowchart of Switch Statement

Flowchart of Switch Statement in Go

Example: switch case in Golang

In the above example, we have assigned 3 to the dayOfWeek variable. Now, the variable is compared with the value of each case statement.

Since the value matches with case 3 , the statement fmt.Println("Tuesday") inside the case is executed.

Note : Unlike other programming languages like C and Java, we don't need to use break after every case. This is because in Go, the switch statement terminates after the first matching case.

Go switch case with fallthrough

If we need to execute other cases after the matching case, we can use fallthrough inside the case statement. For example,

In the above example, the expression in switch matches case 3 so, Tuesday is printed. However, Wednesday is also printed even if the case doesn't match.

This is because we have used fallthrough inside case 3 .

  • Go switch with multiple cases

We can also use multiple values inside a single case block. In such case, the case block is executed if the expression matches with one of the case values.

Let's see an example,

In the above example, we have used multiple values for each case:

  • case "Saturday", "Sunday" - executes if dayOfWeek is either Saturday or Sunday
  • case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" - executes if dayOfWeek is either one of the value

Golang switch without expression

In Go, the expression in switch is optional. If we don't use the expression, the switch statement is true by default. For example,

In the above example, switch doesn't have an expression. Hence, the statement is true .

  • Go switch optional statement

In Golang, we can also use an optional statement along with the expression. The statement and expression are separated by semicolons. For example,

In the above example, we have used the optional statement day := 4 along with the expression day . It matches case 4 and hence, Wednesday is printed.

Table of Contents

  • Flowchart of switch Statement
  • Example Go switch Case in Go
  • Go switch Statement with fallthrough
  • switch without expression

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Programming

Golang's Switch Case: A Technical Guide

  • With Code Example
  • January 16, 2024
Mastering Decision-Making in Go with the Versatile Switch Statement

Discover the incredible power of the switch statement in Golang – a game-changer in decision-making for your code. Unlike the sometimes clunky if-else statements, Go’s switch offers a cleaner and more straightforward way to handle conditions.

In this exploration of Golang switch case, we’ll break down the switch statement, using real-world examples to illustrate its efficiency. Say farewell to the complexities of if-else blocks and welcome a more concise syntax that turns your code into a masterpiece.

This journey isn’t just about making decisions – it’s about making them with finesse. Learn how the switch statement becomes your ally, providing an elegant solution for handling diverse scenarios in your code. It’s not just about control flow; it’s about enhancing your coding experience.

Join us as we navigate the world of Go, unveiling the secrets of the switch statement and empowering you to harness its capabilities. Your coding landscape is on the brink of transformation – are you ready to revolutionize your approach with the unparalleled simplicity and effectiveness of Go’s switch statement? Dive in and let your code do the talking.

Basic Golang Switch Case Statement

The basic syntax of the switch statement looks like this:

In the first example of golang switch case, the switch statement is used to check the value of the day variable. If day matches any of the cases, the corresponding block of code is executed. If none of the cases match, the code inside the default block is executed.

In the second example, the switch statement is used without an expression. Instead, it checks conditions within each case. The first case that evaluates to true executes its corresponding block. If no condition is true , the code inside the default block (if present) is executed.

Fallthrough in Switch

Go’s switch statement does not automatically fall through to the next case. However, you can explicitly use the fallthrough keyword to achieve this behavior:

In this example, when number is 2 , the fallthrough keyword is used after the Two case. This causes the execution to fall through to the next case ( Three ). Without the fallthrough statement, the switch statement would exit after executing the matching case.

Type Switch

Go’s switch statement can also be used for type-switching. It allows you to check the type of an interface variable:

In this example of golang switch case, the checkType function uses a type switch to determine the type of the argument x . The case statements check if x is an int or a string , and the default case handles any other type.

The switch statement in Go is a versatile tool for making decisions based on the value or type of an expression. Whether you’re comparing values, handling multiple conditions, or checking types, the switch statement provides a clean and efficient syntax for expressing decision logic.

Choosing Between switch and if-else in Go

The choice between using a switch statement and a series of if-else statements in Go depends on the specific requirements and readability of the code. Both constructs are used for making decisions based on conditions, but they have different use cases and characteristics.

switch Statement:

Clear and Concise for Multiple Conditions:

  • switch is particularly suitable when there are multiple conditions to check against a single value.
  • It provides a clean and concise syntax, especially when comparing a value against multiple possible values.

Easier to Read and Maintain:

  • switch statements are often easier to read and maintain when there are several possible cases.
  • The structure of a switch statement can make the code more organized and comprehensible.

Type Switching:

  • switch statements can be used for type-switching when checking the type of an interface variable.

Fallthrough:

  • switch allows the use of fallthrough to execute the next case after a match. This can be useful in certain scenarios.

Example of a switch statement:

if-else Statements:

Flexible Conditions:

  • if-else statements are more flexible when dealing with complex conditions that might not fit well in a switch .
  • They are suitable for scenarios where conditions are more dynamic or involve multiple variables.

Readable for Few Conditions:

  • For a small number of conditions or a simple binary decision, if-else statements can be more readable.

Comparisons and Range Checks:

  • if-else statements are suitable for range checks, mathematical comparisons, and boolean conditions.

Example of if-else statements:

When to Use Each:

Opt for switch in the Following Scenarios:

  • When dealing with multiple conditions for a single value.
  • In situations where the code requires checking against numerous possible values.
  • When type-switching becomes necessary.

Choose if-else under the Following Circumstances:

  • When conditions are dynamic and may involve multiple variables.
  • If there are only a few conditions to check.
  • When conditions involve complex boolean expressions.

Considerations:

Readability:

  • Consider the readability and clarity of the code. Choose the construct that makes the code more understandable for future readers.

Code Style:

  • Follow the code style of your team or project. Consistency in code style enhances collaboration.

Specific Requirements:

  • Choose the construct that best fits the specific requirements of the decision logic.

To wrap it up, when navigating the diverse landscape of decision-making in your code, both switch and if-else statements offer unique strengths. The selection between them hinges on the intricacy of your conditions and your code’s readability objectives. Opt for the switch statement when aiming for clarity and conciseness with value-based conditions. On the flip side, embrace the flexibility of if-else when dealing with more intricate or adaptable conditions.

Have thoughts to share on your preference or experiences with these constructs? We’d love to hear from you! Drop a comment below and let’s continue the conversation. Your insights could be the key to helping fellow developers make informed decisions in their coding journeys.

  • Control flow
  • Switch statement

Related Posts

Security best practices for go applications.

In the realm of software development, security is not a mere afterthought but a fundamental cornerstone upon which robust and trustworthy applications are built.

Continuous Improvement and Code Reviews

In the fast-paced world of software development, staying ahead of the curve is paramount. One of the cornerstones of achieving excellence in software engineering is the practice of continuous improvement, and a crucial tool in this journey is the process of code reviews.

Database Integration in GoLang Fiber

In web development, the integration of a database is often a crucial step in building data-driven web applications. A web application’s ability to store, retrieve, and manipulate data is a defining factor in its functionality and utility.

Golang Cheatsheet - PDF Download

Go in a Nutshell Imperative language Statically typed Syntax tokens similar to C (but less parentheses and no semicolons) and the structure to Oberon-2 Compiles to native code (no JVM) No classes, but structs with methods Interfaces No implementation inheritance.

Chapter 2: Setting Up the Environment for GIN Framework

Embarking on a journey in web development often starts with choosing the right tools for the job. In this comprehensive guide, we’ll walk you through the process of installing Go programming language and Gin Framework, a lightweight and flexible web framework for Go.

Golang GORM Hooks

In the dynamic world of GoLang development, efficient data management is crucial for building robust and scalable applications. GORM, a popular Object Relational Mapper (ORM) for Go, provides a powerful set of hooks that allow developers to intervene at various stages of the database lifecycle.

Format, minify, visualize and validate JSON.

Compare two JSON objects.

Validate JSON schema online

Encode and decode Base64.

Encode and decode URL.

Generate UUIDs in v4 and other versions.

Generate cryptographic hashes from your text input using a wide variety of algorithms.

Generate cryptographic hashes from your file using a wide variety of algorithms.

Decode and validate JSON Web Tokens.

View CSV data in a table.

Convert CSV to JSON.

Convert JSON to CSV.

Golang Switch: Working with Switch Statements in Go

Understanding golang switch statements.

Switch statements are a powerful and efficient way to organize and process different cases in Go programming, commonly known as Golang. In this article, we'll explore how switch statements work in Go, with practical examples to help you understand their usage and benefits. By the end of this tutorial, you'll be proficient in using Golang switch statements to streamline your code.

Basic Syntax of Golang Switch Statements

In Golang, the switch statement allows you to select and execute a block of code based on the value of a specific expression or variable. The basic syntax for a Golang switch statement is as follows:

Golang Switch Statement Examples

Let's dive into some examples to understand better how Golang switch statements work. These examples will cover different scenarios and help you gain clarity on the practical usage of switch statements in Go programming.

Example 1: Basic Golang Switch Statement

In this example, we'll create a simple Golang switch statement to check the day of the week. Depending on the day, our program will print a message:

Example 2: Golang Switch with Multiple Case Values

In some cases, you may want to group multiple case values in a single statement. You can do this by separating the values with a comma. Here's an example:

Example 3: Golang Switch with No Expression

You can also create a Golang switch statement with no expression, and it will work similarly to an if-else statement, with the first case that evaluates to 'true' being executed. For example:

Final Thoughts on Golang Switch Statements

In this article, we've explored the fundamental concepts of Golang switch statements, along with practical examples to illustrate their usage in various scenarios. By using switch statements in Go programming, you can improve the readability and efficiency of your code, making it easier to maintain and debug. Keep practicing and exploring more advanced use cases to get the most out of Golang switch statements.

Recommended Reading

  • Tour of Go - Switch
  • Go by Example: Switch

last modified April 11, 2024

In this article we show how to work with switch statement in Golang.

Go switch statement

Go switch statement provides a multi-way execution. An expression or type specifier is compared to the cases inside the switch to determine which branch to execute. Unlike in other languages such as C, Java, or PHP, each case is terminated by an implicit break; therefore, we do not have to write it explicitly.

Switch cases evaluate cases from top to bottom, stopping when a case succeeds. Switch statements work on values of any type, not just integers.

There are two types of switch statements: switch expressions and switch types. We can use commas to separate multiple expressions in the same case statement. The switch without an expression is an alternate way to express if/else logic.

The default statement can be used for a branch that is executed, when no other cases fit. The default statement is optional.

Go switch example

The following is a simple example of a switch statement in Go.

In the code example, we find out the current weekday and print the corresponding message.

The switch statement takes an expresssion, which evaluates to the current weekday.

If the weekday evaluates to time.Monday , we print the "Today is Monday" message.

Go switch multiple expressions

The example prints either weekday or weekend, depending on the evaluation of multiple expressions in two case statements.

Go switch default

The default statement can be used for all the values that do not fit the specified cases.

Go switch optional statement

An optional initializer statement may precede a switch expression. The initializer and the expression are separated by semicolon.

In the code example, we have both the switch initializer and the expression. The switch statement determines if the value is even or odd.

The num := 6 is the switch initializer and the num % 2 is the switch expression.

Go switch break statement

Go uses an implicit break statement for each case. This is different from languages like C or Java, where the break is necessary. We can also explicitly specify break when needed.

In the code example, we loop through a string which contains white spaces. Only non-white spaces are printed.

If we encounter the specified three white spaces, we terminate the switch statement with break .

Go switch without expression

Depending on the current hour, the example prints AM or PM .

Go switch fallthrough

We can use the fallthrough keyword to go to the next case.

Go type switch

In the code example, we print the data type of a value.

Switch Statement

This is tutorial number 10 in Golang tutorial series .

What is a switch statement?

A switch is a conditional statement that evaluates an expression and compares it against a list of possible matches and executes the corresponding block of code. It can be considered as an idiomatic way of replacing complex if else clauses.

An example program is worth a hundred words. Let’s start with a simple example which will take a finger number as input and outputs the name of that finger :) . For example, 1 is thumb, 2 is index, and so on.

Run in playground

In the above program switch finger in line no. 10, compares the value of finger with each of the case statements. The cases are evaluated from top to bottom and the first case which matches the expression is executed. In this case, finger has a value of 4 and hence

is printed.

Duplicate cases are not allowed

Duplicate cases with the same constant value are not allowed. If you try to run the program below, the compiler will complain ./prog.go:19:7: duplicate case 4 in switch previous case at ./prog.go:17:7

Default case

We have only 5 fingers in our hands. What will happen if we input an incorrect finger number? This is where the default case comes into the picture. The default case will be executed when none of the other cases match.

In the above program finger is 8 and it does not match any of the cases and hence incorrect finger number in the default case is printed. It’s not necessary that default should be the last case in a switch statement. It can be present anywhere in the switch.

You might also have noticed a small change in the declaration of finger . It is declared in the switch itself. A switch can include an optional statement that is executed before the expression is evaluated. In line no. 8, finger is first declared and then used in the expression. The scope of finger in this case is limited to the switch block.

Multiple expressions in case

It is possible to include multiple expressions in a case by separating them with comma.

The above program finds whether letter is a vowel or not. The code case "a", "e", "i", "o", "u": in line no. 11 matches any of the vowels. Since i is a vowel, this program prints

Expressionless switch

The expression in a switch is optional and it can be omitted. If the expression is omitted, the switch is considered to be switch true and each of the case expression is evaluated for truth and the corresponding block of code is executed.

In the above program, the expression is absent in switch and hence it is considered as true and each of the cases is evaluated. case num >= 51 && num <= 100: in line no. 12 is true and the program prints

This type of switch can be considered as an alternative to multiple if else clauses.

Fallthrough

In Go, the control comes out of the switch statement immediately after a case is executed. A fallthrough statement is used to transfer control to the first statement of the case that is present immediately after the case which has been executed.

Let’s write a program to understand fallthrough. Our program will check whether the input number is less than 50, 100, or 200. For instance, if we input 75, the program will print that 75 is less than both 100 and 200. We will achieve this using fallthrough .

Switch and case expressions need not be only constants. They can be evaluated at runtime too. In the program above num is initialized to the return value of the function number() in line no. 14. The control comes inside the switch and the cases are evaluated. case num < 100: in line no. 18 is true and the program prints 75 is lesser than 100 . The next statement is fallthrough . When fallthrough is encountered the control moves to the first statement of the next case and also prints 75 is lesser than 200 . The output of the program is

fallthrough should be the last statement in a case . If it is present somewhere in the middle, the compiler will complain that fallthrough statement out of place .

Fallthrough happens even when the case evaluates to false

There is a subtlety to be considered when using fallthrough . Fallthrough will happen even when the case evaluates to false.

Please consider the following program.

In the above program, num is 25 which is less than 50 and hence the case in line no. 9 evaluates to true. A fallthrough is present in line no. 11. The next case case num > 100: in line no. 12 is false since num < 100. But fallthrough doesn’t consider this. Fallthrough will happen even though the case evaluates to false.

The program above will print

So be sure that you understand what you are doing when using fallthrough.

One more thing is fallthrough cannot be used in the last case of a switch since there are no more cases to fallthrough. If fallthrough is present in the last case, it will result in the following compilation error.

Breaking switch

The break statement can be used to terminate a switch early before it completes. Let’s just modify the above example to a contrived one to understand how break works.

Let’s add a condition that if num is less than 0 then the switch should terminate.

In the above program num is -5 . When the control reaches the if statement in line no. 10, the condition is satisfied since num < 0. The break statement terminates the switch before it completes and the program doesn’t print anything :).

Breaking the outer for loop

When the switch case is inside a for loop , there might be a need to terminate the for loop early. This can be done by labeling the for loop and breaking the for loop using that label inside the switch statement. Let’s look at an example.

Let’s write a program to generate a random even number.

We will create an infinite for loop and use a switch case to determine whether the generated random number is even. If it is even, the generated number is printed and the for loop is terminated using its label. The Intn function of the rand package is used to generate non-negative pseudo-random numbers.

In the program above, the for loop is labeled randloop in line no. 9. A random number is generated between 0 and 99 (100 is not included) using the Intn function in line no. 11. If the generated number is even, the loop is broken in line no. 14 using the label.

This program prints,

Please note that if the break statement is used without the label, the switch statement will only be broken and the loop will continue running. So labeling the loop and using it in the break statement inside the switch is necessary to break the outer for loop.

This brings us to the end of this tutorial. There is one more type of switch called type switch . We will look into this when we learn about interfaces .

Please share your valuable comments and feedback. Please consider sharing this tutorial tutorial on twitter or LinkedIn . Have a good day.

Next tutorial - Arrays and Slices

golang assignment in switch

The switch statement lets you check multiple cases. You can see this as an alternative to a list of if-statements that looks like spaghetti. A switch statement provides a clean and readable way to evaluate cases.

While the switch statement is not unique to Go, in this article you will learn about the switch statement forms in golang.

The basic syntax of a switch statement is:

You can also check conditions:

The second form of a switch statement is not to provide any determined value (which is actually defaulted to be true).

Instead it test different conditions in each case branch. So what is a condition?

A condition can be x > 10 or x == 8 .

The code of the branch is executed when the test result of either branch is true.

The third form of a switch statement is to include an initialization statement:

Variable var1 can be any type, and val1 and val2 can be any value of the same type.

The type is not limited to a constant or integer, but must be the same type; The front braces {must be on the same line as the switch keyword.

You can test multiple potentially eligible values at the same time, using commas to split them, for example: case val1, val2, val3: .

Note Once a branch has been successfully matched, the entire switch code block is exited after the corresponding code is executed, that is, you do not need to use the break statement specifically to indicate an end.

If you want to continue with the code for subsequent branches after you finish the code for each branch, you can use the fallthrough keyword to achieve the purpose.

The example below demonstrates the use of a switch statement in Go.

  • Data Types in Go
  • Go Keywords
  • Go Control Flow
  • Go Functions
  • GoLang Structures
  • GoLang Arrays
  • GoLang Strings
  • GoLang Pointers
  • GoLang Interface
  • GoLang Concurrency

Switch Statement in Go

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:

Expression Switch

Type 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.

Important Points:

  • Both optstatement and optexpression in the expression switch are optional statements.
  • If both optstatement and 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.
       
       
     

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.

  • The optional statement, i.e., optstatement is similar as in the switch expression.
  • 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 .
     

author

Please Login to comment...

Similar reads.

  • Go Language
  • Go-Control-Flow
  • Top 10 Fun ESL Games and Activities for Teaching Kids English Abroad in 2024
  • Top Free Voice Changers for Multiplayer Games and Chat in 2024
  • Best Monitors for MacBook Pro and MacBook Air in 2024
  • 10 Best Laptop Brands in 2024
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

golang assignment in switch

Social Media Toolkit

Download our all in one automation tool for various social media websites.

golang assignment in switch

Switch statements in Golang

Switch statement is one of the control flow statements in Golang. Switch statement helps you to write concise code. Switch statement can be used for replacing multiple if else statements or if else ladder with one switch statement.

Golang only runs the selected case statement that is matched and does not execute remaining cases following the case that is matched.

Golang automatically provides a break statement for all the cases that are defined, however this behaviour can be overridden by manually placing a fallthrough statement.

In Golang switch cases don’t have to be constant.

Evaluation order of a switch statement

It is important to know that evaluation order of a switch statement is from top to bottom. This means that statements provided at the top of the switch statement will be evaluated before statements provided at the bottom of the switch statement.

This can be confirmed by taking a look at various examples given on this page.

Program to demonstrate a simple switch statement in Golang

Program given below makes use of simple switch statement to evaluate the value of variable a and print appropriate message to the console.

Program output

Above program produces following output:

Switch with no condition

A switch statement with no condition is same as switch true . It means that switch statement acts like a concise way to define if else statements with multiple conditions.

Switch statement with missing expression

Program given below demonstrates a switch statement with a missing expression.

This way of defining switch statement is same as switch true

Switch statement using fallthrough

By default, Golang adds a break statement for every case statement, however if we want to change this behaviour and instead want to continue evaluating the next case statement then we can use the fallthrough statement for achieving similar results.

Program given below effect of follthrough on how cases are evaluated.

Using the default case

If a switch statement fails to match any case then code inside default case block will be executed. This behaviour is demonstrated in the example given below.

In the program given below, no match for x is found therefore the default case block is executed.

Buffer

5 switch statement patterns

golang assignment in switch

Basic switch with default

No condition, fallthrough, exit with break, execution order.

  • A switch statement runs the first case equal to the condition expression.
  • The cases are evaluated from top to bottom, stopping when a case succeeds.
  • If no case matches and there is a default case, its statements are executed.
Unlike C and Java, the case expressions do not need to be constants.

A switch without a condition is the same as switch true.

  • A fallthrough statement transfers control to the next case.
  • It may be used only as the final statement in a clause.

A break statement terminates execution of the innermost for , switch , or select statement.

If you need to break out of a surrounding loop, not the switch, you can put a label on the loop and break to that label. This example shows both uses.

  • First the switch expression is evaluated once.
  • the first one that equals the switch expression triggers execution of the statements of the associated case,
  • the other cases are skipped.

Go step by step

golang assignment in switch

Core Go concepts: interfaces , structs , slices , maps , for loops , switch statements , packages .

Go Tutorial

Go exercises, go switch statement, the switch statement.

Use the switch statement to select one of many code blocks to be executed.

The switch statement in Go is similar to the ones in C, C++, Java, JavaScript, and PHP. The difference is that it only runs the matched case so it does not need a break statement.

Single-Case switch Syntax

This is how it works:

  • The expression is evaluated once
  • The value of the switch expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The default keyword is optional. It specifies some code to run if there is no case match

Single-Case switch Example

The example below uses a weekday number to calculate the weekday name:

Advertisement

The default Keyword

The default keyword specifies some code to run if there is no case match:

All the case values should have the same type as the switch expression. Otherwise, the compiler will raise an error:

Test Yourself With Exercises

Insert the missing parts to complete the following switch statement.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Go Switch - 6 ways of using Switch in Go

Go Switch - 6 ways of using Switch in Go

Sriram Thiagarajan

  • August 17, 2021
  • Web Development

6 ways of using Switch statement in Go

Basic switch.

Switch case is commonly used there are multiple condition checks to be done for a particular variable. It is easier to understand than having multiple if statements in your code.

Switch statement evaluates the expression and executes the block of code that matches from the list of possible choices

In the above program, we have a status variable that can correspond to different values based on its integer value. Business logic suggests the following

1 - In progress

Using the switch statement, we can check the value of the status and print the corresponding value.

Switch with default statement

There are instances when the expression being evaluated will contain a value not present in the list of cases defined. default statement comes to our rescue by executing that case if there is no match with the other case defined.

Switch without condition

Switch statement supports expression less statement when defining. If you just want multiple condition to be check and give those condition in the case, you can remove the expression in the switch statement

Switch with case list

Another common use case will be to have multiple expressions in a case. Multiple expressions are separated by commas.

Switch with fallthrough statement

Execution of the statements in switch goes from top to bottom. When a particular case evaluates to be true, execution of the statement takes place. Control jumps out of the switch after execution of the successful case. fallthrough statement is used to transfer the execution of the code to the first statement of the case after the executed case

Go Fallthrough Explaination

Fallthrough can be used when you want to execute the successive case irrespective of its condition

Status is done Status is done but has some issues

Things to note about fallthrough

  • Fallthrough execute the next case even if the case will evaluate to false. Above example shows that the last case is executed but the condition status > 6 is false.
  • Fallthrough has to be the last statement in your case
  • Fallthrough cannot be present in the last case

Switch with break statement

Execution of the case statements can be stopped by using the break statement.

Status is done

In the above program, when the status is 2 , then the second case gets executed. if condition becomes true and so break is called which sends the control to the end of the switch statement without running the fallthrough statement

Similarly, you can break from a labeled loop by specifying the label after the break statement

for loop without a condition will execute infinite loop until it runs into a break statement. For more info you can have a loop into this blog post.

https://www.eternaldev.com/blog/go-learning-for-loop-statement-in-depth/

status variable will contain a random value between 0 to 5 for each loop iteration. If that value is less than 3, “Waiting for status to complete” is printed. If the value is greater than or equal to 3, “Status is done” is printed and we break the outer for loop.

So this program executes until we get values from 3 to 5 from the random value function.

Practical Assignment - Try these out

Simple app which takes the name of the task and status of the task from the user, and outputs the remaining status for the task using the Switch statement

  • Status list - Created, Sprint Ready, Work in Progress, Completed, Deployed, Verified
  • User input - “Feature A”, “Work in Progress” - Output - 3 steps are pending
  • User input - “Feature C”, “Created” - Output - 5 steps are pending

Use the live code editor below to work on the assignment

Stay tuned by subscribing to our mailing list and joining our Discord community

  • #Web development

Similar Posts

3 Simple ways to center div in 2020

  • November 1, 2021

3 Simple ways to center div in 2020

Golang - 5 different ways of comparing two strings with reasons

  • November 12, 2022

Golang - 5 different ways of comparing two strings with reasons

5 ways to concatenate string in Golang with reasons

  • October 28, 2022

5 ways to concatenate string in Golang with reasons

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

golang multiple case in type switch

when I run the code snippet bellow, it raise a error

a.test undefined (type interface {} is interface with no methods)

It seem the type switch does not take effect.

If I change it to

it's ok now.

yjfuk's user avatar

This is normal behaviour that is defined by the spec (emphasis mine):

The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the beginning of the implicit block in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard .

So, in fact, the type switch does take effect, but the variable a keeps the type interface{} .

One way you could get around this is to assert that foo has the method test() , which would look something like this:

  • 2 is there a way to make it from if to a switch case statement?? –  Kelwin Tantono Commented Sep 22, 2021 at 16:44

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged go or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Fusion September 2024: Where are we with respect to "engineering break even"?
  • No displayport over USBC with lenovo ideapad gaming 3 (15IHU6)
  • Hashable and ordered enums to describe states of a process
  • I'm a little embarrassed by the research of one of my recommenders
  • Children in a field trapped under a transparent dome who interact with a strange machine inside their car
  • Is it a good idea to perform I2C Communication in the ISR?
  • Breaker trips when plugging into wall outlet(receptacle) directly, but not when using extension
  • Humans are forbidden from using complex computers. But what defines a complex computer?
  • How to sum with respect to partitions
  • Does the average income in the US drop by $9,500 if you exclude the ten richest Americans?
  • Is my magic enough to keep a person without skin alive for a month?
  • What is the optimal number of function evaluations?
  • What`s this? (Found among circulating tumor cells)
  • \ExplSyntaxOn problem with new paragraph
  • How can I play MechWarrior 2?
  • Visual assessment of scatterplots acceptable?
  • Why is this bolt's thread the way it is?
  • Does a party have to wait 1d4 hours to start a Short Rest if no healing is available and an ally is only stabilized?
  • What is the first work of fiction to feature a vampire-human hybrid or dhampir vampire hunter as a protagonist?
  • Show that an operator is not compact.
  • how do I fix apt-file? - not working and added extra repos
  • How to go from Asia to America by ferry
  • Gravitational potential energy of a water column
  • How to clean a female disconnect connector

golang assignment in switch

COMMENTS

  1. Go Wiki: Switch

    Type switch. With a type switch you can switch on the type of an interface value (only): func typeName(v interface{}) string { switch v.(type) { case int: return "int" case string: return "string" default: return "unknown" } } You can also declare a variable and it will have the type of each case:

  2. How To Write Switch Statements in Go

    How To Write Switch Statements in Go

  3. The switch statement in Golang

    The switch statement can be used as a replacement for the if-else block. Sometimes it becomes verbose when we use the if-else block. At that point, the switch statement may be beneficial. The switch statement is one of the most important control flow in programming. It improves on the if-else chain in some cases.

  4. : Switch

    switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants. t:= time. Now switch {case t. Hour < 12: fmt. Println ("It's before noon") default: fmt. Println ("It's after noon")} A type switch compares types instead of values. You can use this to discover the type of ...

  5. Go switch case (With Examples)

    In Go, the expression in switch is optional. If we don't use the expression, the switch statement is true by default. For example, // Program to check if it's February or not using switch without expression package main. import "fmt" func main() {. numberOfDays := 28. switch {. case 28 == numberOfDays:

  6. Golang's Switch Case: A Technical Guide

    In this example of golang switch case, the checkType function uses a type switch to determine the type of the argument x.The case statements check if x is an int or a string, and the default case handles any other type.. The switch statement in Go is a versatile tool for making decisions based on the value or type of an expression. Whether you're comparing values, handling multiple ...

  7. Golang Switch: Working with Switch Statements in Go

    In Golang, the switch statement allows you to select and execute a block of code based on the value of a specific expression or variable. The basic syntax for a Golang switch statement is as follows: switch expression { case value1: // code to be executed if expression==value1 case value2: // code to be executed if expression==value2 default ...

  8. Go switch

    In this article we show how to work with switch statement in Golang. $ go version go version go1.22.2 linux/amd64 We use Go version 1.22.2. Go switch statement. Go switch statement provides a multi-way execution. An expression or type specifier is compared to the cases inside the switch to determine which branch to execute.

  9. Go (Golang) Switch Statement Tutorial with Examples

    go. Run in playground. In the above program switch finger in line no. 10, compares the value of finger with each of the case statements. The cases are evaluated from top to bottom and the first case which matches the expression is executed. In this case, finger has a value of 4 and hence. Finger 4 is Ring.

  10. Golang Switch Statement (Syntax & Examples)

    The switch statement lets you check multiple cases. You can see this as an alternative to a list of if-statements that looks like spaghetti. A switch statement provides a clean and readable way to evaluate cases. While the switch statement is not unique to Go, in this article you will learn about the switch statement forms in golang. Syntax

  11. A Tour of Go

    Switch statements

  12. A Tour of Go

    A type switch is a construct that permits several type assertions in series. A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value. switch v := i.(type) {. case T: // here v has type T. case S:

  13. how to use a `switch` statement in Go

    1. To add to what Daniel wrote — basically the switch statement (unless it's a type switch but let's not digress) has two forms: switch { // note the absense of any expression here. case bool_expr_1:

  14. Switch Statement in Go

    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: Expression Switch. Type Switch. Expression Switch. Expression switch is similar to switch statement ...

  15. Switch statements in Golang

    Switch statement is one of the control flow statements in Golang. Switch statement helps you to write concise code. Switch statement can be used for replacing multiple if else statements or if else ladder with one switch statement. Golang only runs the selected case statement that is matched and does not execute remaining cases following the case that is matched. Golang automatically provides ...

  16. 5 switch statement patterns · YourBasic Go

    Basic switch with default. A switch statement runs the first case equal to the condition expression. The cases are evaluated from top to bottom, stopping when a case succeeds. If no case matches and there is a default case, its statements are executed. switch time.Now().Weekday() {. case time.Saturday:

  17. Go switch Statement

    The switch Statement. Use the switch statement to select one of many code blocks to be executed. The switch statement in Go is similar to the ones in C, C++, Java, JavaScript, and PHP. The difference is that it only runs the matched case so it does not need a break statement.

  18. Go Switch

    Simple app which takes the name of the task and status of the task from the user, and outputs the remaining status for the task using the Switch statement. Status list - Created, Sprint Ready, Work in Progress, Completed, Deployed, Verified. User input - "Feature A", "Work in Progress" - Output - 3 steps are pending.

  19. go

    The one statement multiple assignment, which uses implicit temporary variables, is equivalent to (a shorthand for) the two multiple assignment statements, which use explicit temporary variables. Your fibonacci example translates, with explicit order and temporary variables, to: package main. import "fmt". func fibonacciMultiple() func() int {.

  20. syntax

    A short variable declaration uses the syntax: ShortVarDecl = IdentifierList ":=" ExpressionList . It is a shorthand for a regular variable declaration with initializer expressions but no types: "var" IdentifierList = ExpressionList . Assignments. Assignment = ExpressionList assign_op ExpressionList . assign_op = [ add_op | mul_op ] "=" .

  21. go

    This is normal behaviour that is defined by the spec (emphasis mine): The TypeSwitchGuard may include a short variable declaration. When that form is used, the variable is declared at the beginning of the implicit block in each clause. In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the ...