← Back to Go Course | Chapter 7: Interfaces | Lesson 4 of 7

Type Switches

A type switch lets you ask a mystery box 'what kind of thing are you, really?' and run different code depending on the answer.

Basic Type Switch

A type switch uses the special syntax i.(type) inside a switch statement to branch based on the interface value's actual concrete type, running the matching case's code.

Example: Basic Type Switch

markup
package main

import "fmt"

func describe(i interface{}) {
	switch v := i.(type) {
	case int:
		fmt.Println("int:", v*2)
	case string:
		fmt.Println("string:", v+"!")
	default:
		fmt.Println("unknown type")
	}
}

func main() {
	describe(21)
	describe("hi")
	describe(3.14)
}

Grouping Multiple Types in One Case

A single case in a type switch can list several types separated by commas, useful when multiple types should be handled identically -- though inside that combined case, v keeps the original interface type rather than a specific one.

Example: Grouping Multiple Types in One Case

markup
package main

import "fmt"

func classify(i interface{}) string {
	switch i.(type) {
	case int, int64, float64:
		return "numeric"
	case string:
		return "text"
	default:
		return "other"
	}
}

func main() {
	fmt.Println(classify(5))
	fmt.Println(classify("hi"))
	fmt.Println(classify(true))
}

Handling the nil Case

A type switch can include a 'case nil' to explicitly handle an interface value that holds no concrete type at all, which is worth doing separately since a nil interface behaves differently from a nil pointer stored inside a non-nil interface.

Example: Handling the nil Case

markup
package main

import "fmt"

func report(i interface{}) {
	switch i.(type) {
	case nil:
		fmt.Println("no value provided")
	case int:
		fmt.Println("got an int")
	default:
		fmt.Println("got something else")
	}
}

func main() {
	report(nil)
	report(7)
}
Common Mistakes
  1. Forgetting the special switch v := i.(type) syntax only works directly in a switch statement, not as a standalone expression.
  2. Not handling the default case, silently ignoring types you didn't anticipate.
  3. Reusing the same variable name shadowed per case and being confused about its type in each branch (it's actually correctly re-typed per case, this trips up newcomers).
Chapter Summary
  • A type switch, 'switch v := i.(type) { }', branches based on the concrete type stored in an interface value.
  • Each case names a concrete type, and inside that case, the variable has that specific type.
  • A default case catches any type not explicitly listed.
  • Type switches are the idiomatic way to handle several possible concrete types held in one interface value.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.