A switch is a multi-way branch statement used in place of multiple if-else statements but can also be used to find out the dynamic type of an interface variable.
A type switch is a construct that performs multiple type assertions to determine the type of variable (rather than values) and runs the first matching switch case of the specified type. It is used when we do not know what the interface{} type could be.
Example 1:
C
package main
import (
"fmt"
)
func main() {
var value interface{} = "GeeksforGeeks"
switch t := value.(type){
case int64:
fmt.Println( "Type is an integer:" , t)
case float64:
fmt.Println( "Type is a float:" , t)
case string:
fmt.Println( "Type is a string:" , t)
case nil:
fmt.Println( "Type is nil." )
case bool :
fmt.Println( "Type is a bool:" , t)
default :
fmt.Println( "Type is unknown!" )
}
}
|
Output:
Type is a string: GeeksforGeeks
The switch can have multiple value cases for different types and is used to select a common block of code for many similar cases.
Note: Golang does not needs a ‘break’ keyword at the end of each case in the switch.
Example 2:
C
package main
import (
"fmt"
)
func find_type(value interface{}) {
switch t := value.(type) {
case int , float64:
fmt.Println( "Type is a number, either an int or a float:" , t)
case string, bool :
fmt.Println( "Type is either a string or a bool:" , t)
case * int , * bool :
fmt.Println( "Type is a pointer to an int or a bool:" , t)
default :
fmt.Println( "Type unknown!" )
}
}
func main() {
var v interface{} = "GeeksforGeeks"
find_type(v)
v = 34.55
find_type(v)
}
|
Output:
Type is either a string or a bool: GeeksforGeeks
Type is a number, either an int or a float: 34.55
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!