Switch Typeof Operator in Golang

Learn via video courses
Topics Covered

Overview

In Go, a type-switch is similar to a switch statement, but it has types. In this post, we will go over type switches in Go in depth. But first, we must comprehend the switch statement, and then we will see the Switch Typeof Operator in Golang with some use cases.

What is a Switch Statement?

In Go, a Switch Statement is a control flow statement that allows for multiple branches of execution based on the value of an expression. The expression is evaluated and the corresponding case that matches the value of the expression is executed. If no case matches the value of the expression, the default case (if present) is executed. Switch statements function similarly to if-else blocks.

For Example:

Output:

Run the code!

Explanation of the Code:

  • In the above code, A switch statement is used to match the given string argument with four different cases (a, b, c, d).
  • Each case has a corresponding print statement to output a specific result based on the case.
  • In the main function, the f function is called twice with different string arguments.
  • The output of the program will be "A" and "C" based on the inputs passed to the function.

In Golang there are two types of Switch Statements:

Switch Expressions and Switch Types:.

What are Switch Expressions in Golang?

Expression: Expression in the switch is similar to switch statement. It makes the code execution easy by checking for a particular expression from the code. Switch Expression can be used as individual switch expression or multiple-expression which we will see further in the article.

Syntax:

Explanation of the Syntax:

  • Optstatement and Optexpression are optional statetments.
  • If both Optexpression and Optstatement are added then we will use ; to seprate them individually.
  • If there is a no expression by default it's true.
  • Default is also an optional statement.
  • We can implement Multiple Expressions in Golang using ,.

For Example:

Output:

Explanation:

  • In the above code declares a variable named value with an int data type and assigns the value 2 to it. This variable will be used in the switch statement.
  • The switch statement takes the value of value as input and executes a block of code based on the value.
    • Case 1: If the value of value is equal to 1, the code inside the first case is executed, and the program prints "Expression1" to the console.
    • Case 2: If the value of value is equal to 2, the code inside the second case is executed, and the program prints "Expression2" to the console.
    • Case 3: If the value of value is equal to 3, the code inside the third case is executed, and the program prints "Expression3" to the console.
    • Default Case: If the value of value does not match any of the above cases, the code inside the default case is executed, and the program prints "Invalid" to the console.
  • It finally prints, Expression2 as a desired output.

Run the code!

We can also implement with optional statement for example:

Output:

Run the code!

Explanation:

  • Inside the main function, there is a switch statement that assigns the value 4 to the variable value and uses it to check against the different cases. The switch statement checks if the value of the variable value is equal to 1, 2, 3 or 4.
  • If the value of value matches any of these cases, it will execute the corresponding block of code, which in this case is just a single line that prints a string to the console.
  • If the value of value does not match any of the cases, the default case will be executed, which in this case is also just a single line that prints the string Invalid to the console.
    • In this example, the output of the program will be Expression 4, because the value of the variable value is 4, which is the case that is being matched in the switch statement.

How to implement Multiple Expressions Example:

Output:

Run the code!

Explanation:

  • In the above code, we used the time package to determine the current day of the week and then uses a switch statement to check whether it's a weekday or a weekend. If it's a weekday, it prints weekday, and if it's a weekend, it prints weekend.
  • The above code, shows how we can implement multiple expressions in golang.

What are Type Switches in Golang?

A Type-Switch in golang is a switch block where unlike the switch statement we have values given to the switch, here we have values in the form of interface which is data-type. It will check the interface type and switch to the specific type to perform some operations.

Syntax:

Explanation:

  • Optstatement and Optexpression are optional statements.
  • If both Optexpression and Optstatement are added then we will use ; to separate them individually.
  • Multiple values can be used by separating it with ,.
  • Default is also an optional statement.
  • Typeswitchexpression is an expression whose result types.
  • We have the option to define type either manually or by using := operator which will be taken care of when the code came to that specific case.

For Example:

Output:

Run the code!

Explanation:

  • In the above code, an interface i with the value "Scaler", where a switch statement is used to determine the type of the interface. The type of interface is stored in the v variable.
  • Different case statements are used to check if the type of the interface is an integer, floating point number, string, nil, or boolean. If the type matches one of the case statements, a message is printed to the console indicating the type of the interface.
  • If the type of the interface does not match any of the case statements, the default case is executed, and a message indicating that the type is unknown is printed on the console.

Another Example:

Output:

Run the code!

Explanation:

  • A function named t is defined which takes an argument of type interface{} and returns a string value.
  • Inside the t function, a switch statement is used to check the type of the value stored in the I interface.
  • There are three cases defined in the switch statement:
    • Case 1: If the value is of type string, the function returns "A string value".
    • Case 2: If the value is of type int, the function returns "A number".
    • Default Case: If the value is of any other type, the function returns "Other".
  • In the main function a variable a of type interface{} and assigning it the value Scaler.
  • The t function is called with an as the argument and the returned value is printed to the console using the fmt.Println function.
  • The final output of the code will be A string value.

Why are Type Switches Important in Golang?

Type switches are used to determine the type of an interface variable at runtime. Go is a statically-typed language, which means that the type of a variable is determined at compile-time. However, Go also has support for interfaces, which allow variables to have multiple types. In such cases, type switches can be used to determine the actual type of a variable that is stored in an interface.

Type switches are particularly useful when working with the interface{} type, which can hold any value of any type. By using a type switch, you can determine the actual type of the value stored in an interface{} variable, and then cast it to the appropriate type so you can use it in your code.

  • Type-assertions: Type switches can be used to perform type-assertions, which is a way to check if an interface variable holds a value of a specific type. This can be useful for validating data in a program.
  • Handling Unknown Types: Type switches can be used to handle unknown types in a program. , For example,, when receiving data from an external source, you may not know the type of the data beforehand. A type switch can be used to determine the type of data and handle it accordingly.

Uses of Type Switches in Golang.

  • Determining the Type of an Interface Variable: Type switches can be used to determine the actual type of a variable stored in an interface at runtime. This is useful when working with interfaces and other dynamic types in Go.
  • Unmarshalling Data: Type switches are used in several standard library functions such as json.Unmarshal, encoding/xml.Unmarshal, etc. which helps to unmarshal the data into the specific types.

Type Switches V/S Switch Cases

Type Switche are different from Switch Cases or cases.

Type-SwitchesSwitch Cases
These are multiway branch-statement that are used to compare different typesThese are multiway branch-statement that are used to compare different values.
Type-switches are more useful as it is capable of comparing values as well as typesSwitch-cases are less useful as it only works for values
Type switches can be used to cast an interface variable to a specific typeSwitch cases do not involve type casting
Type switches are mostly used to work with interfaces and dynamic typesSwitch cases are used to execute different branches of code based on the value of an expression.

Conclusion

  • A Switch Statement is a type of control flow that looks for a condition to meet and then runs specified code based on that matched value.
  • Type-Switch is similar to a switch statement but instead of checking values and running specific code, it will check for type to switch from one case to another.
  • Type switches are important in Go because they allow you to determine the actual type of a variable stored in an interface at runtime, which is necessary for working with interfaces and other dynamic types in Go.
  • We also get to know the difference between both Type-Switch and Switch Statement.