Menu
Coddy logo textTech

Type Switch

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 30 of 107.

When you need to check an interface value against multiple possible types, writing separate type assertions becomes tedious. A type switch provides a cleaner way to handle this by combining a switch statement with type checking.

The syntax looks like a regular switch, but uses the special .(type) syntax:

func describe(value any) {
    switch v := value.(type) {
    case int:
        fmt.Println("Integer:", v*2)
    case string:
        fmt.Println("String of length:", len(v))
    case bool:
        fmt.Println("Boolean:", v)
    default:
        fmt.Println("Unknown type")
    }
}

The variable v takes on the concrete type within each case block. In the int case, v is an int, so you can perform arithmetic. In the string case, v is a string, so you can call len().

You can also group multiple types in a single case:

switch v := value.(type) {
case int, int64, float64:
    fmt.Println("It's a number")
case string:
    fmt.Println("String:", v)
}

When grouping types, v remains the original interface type since the compiler can't determine which specific type matched. The default case handles any type not explicitly listed, making your code robust against unexpected inputs.

challenge icon

Challenge

Easy

Let's build a value classifier that uses type switches to analyze different types of data and produce meaningful descriptions. You'll create a system that can handle multiple value types and provide type-specific information about each one.

You'll organize your code across two files:

  • classifier.go: Create a function called Classify that takes a value of type any and returns a descriptive string. Use a type switch to handle the following types:
    • For int: return whether the number is positive, negative, or zero
    • For string: return the string's length category (short, medium, or long)
    • For bool: return a human-readable representation
    • For float64: return whether it's a whole number or has decimals
    • For any other type: return an unknown type message
  • main.go: Read values from input, convert them to appropriate types, store them in any variables, and use your Classify function to analyze each one. Print the classification result for each value.

The following inputs will be provided:

  • Line 1: An integer value
  • Line 2: A string value
  • Line 3: A boolean value (true or false)
  • Line 4: A float value

Your Classify function should return strings in these formats:

  • For int: Integer: positive, Integer: negative, or Integer: zero
  • For string: String: short (length 1-5), String: medium (length 6-10), or String: long (length > 10)
  • For bool: Boolean: yes (if true) or Boolean: no (if false)
  • For float64: Float: whole (if no decimal part) or Float: decimal (if has decimal part)
  • For unknown types: Unknown type

For example, given -5, hello, true, and 3.14, your output should be:

Integer: negative
String: short
Boolean: yes
Float: decimal

The type switch gives you access to the concrete type within each case, so you can perform type-specific operations like comparing integers to zero or checking string length directly on the switched variable.

Cheat sheet

A type switch allows you to check an interface value against multiple possible types in a clean way, combining a switch statement with type checking.

Basic type switch syntax using .(type):

func describe(value any) {
    switch v := value.(type) {
    case int:
        fmt.Println("Integer:", v*2)
    case string:
        fmt.Println("String of length:", len(v))
    case bool:
        fmt.Println("Boolean:", v)
    default:
        fmt.Println("Unknown type")
    }
}

The variable v takes on the concrete type within each case block, allowing type-specific operations.

You can group multiple types in a single case:

switch v := value.(type) {
case int, int64, float64:
    fmt.Println("It's a number")
case string:
    fmt.Println("String:", v)
}

When grouping types, v remains the original interface type. The default case handles any type not explicitly listed.

Try it yourself

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Read the integer value
	var intStr string
	fmt.Scanln(&intStr)
	intVal, _ := strconv.Atoi(intStr)

	// Read the string value
	var strVal string
	fmt.Scanln(&strVal)

	// Read the boolean value
	var boolStr string
	fmt.Scanln(&boolStr)
	boolVal, _ := strconv.ParseBool(boolStr)

	// Read the float value
	var floatStr string
	fmt.Scanln(&floatStr)
	floatVal, _ := strconv.ParseFloat(floatStr, 64)

	// TODO: Store each value in an 'any' variable
	// TODO: Call Classify() for each value and print the result

}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming