How to Use Type Switch in Go: Syntax and Examples
In Go, use a
type switch to check the dynamic type of an interface variable. It uses the syntax switch v := x.(type) where x is an interface, and each case handles a specific type.Syntax
A type switch lets you compare the type of an interface variable against multiple types. The syntax is:
switch v := x.(type) {
case T1:
// v has type T1
case T2:
// v has type T2
default:
// no match
}Here, x is an interface value. The variable v inside each case has the type matched in that case. The default case runs if no types match.
go
switch v := x.(type) { case int: // v is int case string: // v is string default: // v is unknown type }
Example
This example shows how to use a type switch to print different messages depending on the type of the variable.
go
package main import "fmt" func describe(i interface{}) { switch v := i.(type) { case int: fmt.Printf("Integer: %d\n", v) case string: fmt.Printf("String: %q\n", v) case bool: fmt.Printf("Boolean: %t\n", v) default: fmt.Printf("Unknown type %T\n", v) } } func main() { describe(42) describe("hello") describe(true) describe(3.14) }
Output
Integer: 42
String: "hello"
Boolean: true
Unknown type float64
Common Pitfalls
Common mistakes when using type switches include:
- Trying to use a type switch on a non-interface value. It only works on interface types.
- Forgetting to use
.(type)syntax in the switch statement. - Not handling the
defaultcase, which can cause unexpected behavior if an unknown type is passed.
Example of wrong and right usage:
go
package main import "fmt" func wrong(i interface{}) { // This will cause a compile error because .(type) is missing // switch v := i { // case int: // fmt.Println("int", v) // } } func right(i interface{}) { switch v := i.(type) { case int: fmt.Println("int", v) default: fmt.Println("unknown type") } } func main() { right(10) }
Output
int 10
Quick Reference
| Concept | Description |
|---|---|
| switch v := x.(type) | Start a type switch on interface variable x, assigning matched type to v |
| case T: | Handle when x has type T, v has type T inside this case |
| default: | Handle any type not matched by previous cases |
| v | Variable holding the value with the matched type inside each case |
Key Takeaways
Use type switch with syntax 'switch v := x.(type)' to check interface variable types.
Each case in the switch handles a specific type and assigns it to variable v.
Always include a default case to handle unexpected types safely.
Type switches only work on interface types, not concrete types.
Remember to use .(type) syntax; omitting it causes compile errors.