Type Switches
Start with Type Switches
A type switch chooses a branch according to the dynamic type stored in an interface value.
What you’ll learn
- Explain the main purpose of type switches.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Write switch x := value.(type) and provide case int:, case string: and other branches. Within a single-type case, x has that concrete type, so you can use its operations without an extra assertion.
The .(type) syntax is permitted only in a type switch. If no case matches, the default branch handles the value. A type switch is useful for a small, explicitly supported set of different data types.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func describe(value any) {
switch x := value.(type) {
case int:
fmt.Println("Integer doubled:", x*2)
case string:
fmt.Println("Text:", x)
default:
fmt.Println("Another type")
}
}
func main() {
describe(4)
describe("Go")
describe(true)
}
Output
Integer doubled: 8
Text: Go
Another typeTrace what the program does
The dynamic integer selects the int branch and prints 8. The string selects the string branch. A bool matches neither and reaches default.
Avoid common mistakes
- The special
.(type)form is not a general-purpose expression. - Only one matching type-switch case runs for a given value.
Try it yourself
Add a float64 case that prints twice the input value, then call describe(2.5).
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Type Switches in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.