CodeNebula
Go🔧Core Languagebeginner

Type Switches

Go · Core Language · Run with go run

Explanation

A type switch is a control structure that branches on the dynamic type of an interface value. The special syntax `switch v := i.(type)` binds `v` to the concrete value in each case, with the right static type. It is the idiomatic way to handle a value that may be one of several types.

Real-World Scenario

A JSON decoder unmarshals arbitrary data into `any`. A type switch dispatches on whether each value is a `string`, `float64`, `bool`, `map[string]any`, or `[]any` — building a typed structure from untyped input.

Quick Snippet

snippet.go
func describe(i any) string {
    switch v := i.(type) {
    case int:
        return fmt.Sprintf("int: %d", v)
    case string:
        return fmt.Sprintf("string of length %d", len(v))
    case bool:
        return fmt.Sprintf("bool: %t", v)
    case nil:
        return "nil value"
    default:
        return fmt.Sprintf("unknown type %T", v)
    }
}

Full Example

type_switches.go
// Compile: go run type_switches.go
// Output:
//   int: 42
//   string of length 5
//   bool: true
//   nil value
//   unknown type []int
package main

import "fmt"

func describe(i any) string {
	switch v := i.(type) {
	case int:
		return fmt.Sprintf("int: %d", v)
	case string:
		return fmt.Sprintf("string of length %d", len(v))
	case bool:
		return fmt.Sprintf("bool: %t", v)
	case nil:
		return "nil value"
	default:
		return fmt.Sprintf("unknown type %T", v)
	}
}

func main() {
	for _, v := range []any{42, "hello", true, nil, []int{1, 2}} {
		fmt.Println(describe(v))
	}
}
Run command
go run type_switches.go