0Pricing
Go Academy · Lesson

Type Assertions and Type Switches

Safe type assertions and switch patterns

Type Assertions and Type Switches is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Type Assertions

A type assertion extracts the concrete value from an interface. The syntax is x.(T):

package main
import "fmt"

func main() {
    var i interface{} = "hello"
    s := i.(string)          // panics if wrong type
    fmt.Println(s, len(s))   // hello 5
}

Safe Two-Value Assertion

Use the comma-ok form to avoid panics on wrong types:

package main
import "fmt"

func main() {
    var i interface{} = 42
    s, ok := i.(string)
    fmt.Println(s, ok)  // "" false
    n, ok := i.(int)
    fmt.Println(n, ok)  // 42 true
}

Type Switch

A type switch compares the dynamic type of an interface value against multiple types:

package main
import "fmt"

func describe(i interface{}) string {
    switch v := i.(type) {
    case int:    return fmt.Sprintf("int: %d", v)
    case string: return fmt.Sprintf("string: %q", v)
    case bool:   return fmt.Sprintf("bool: %v", v)
    default:     return fmt.Sprintf("unknown: %T", v)
    }
}

func main() {
    fmt.Println(describe(42))
    fmt.Println(describe("hi"))
    fmt.Println(describe(3.14))
}

Type Switch on error

Type switches are especially useful for categorizing errors:

package main
import ("errors"; "fmt")

type NotFoundError struct{ Name string }
func (e *NotFoundError) Error() string { return e.Name + " not found" }

type PermError struct{}
func (e *PermError) Error() string { return "permission denied" }

func handle(err error) {
    switch e := err.(type) {
    case *NotFoundError: fmt.Println("missing:", e.Name)
    case *PermError:     fmt.Println("perm error")
    default:             fmt.Println("other:", e)
    }
}

func main() {
    handle(&NotFoundError{"user"})
    handle(errors.New("generic"))
}

Asserting to an Interface

You can assert to another interface type, not just concrete types. Useful to check if an object supports optional behavior:

package main
import "fmt"

type Flusher interface{ Flush() }

type Writer interface{ Write(string) }

type BufferedWriter struct{ buf string }
func (b *BufferedWriter) Write(s string) { b.buf += s }
func (b *BufferedWriter) Flush()         { fmt.Println(b.buf); b.buf = "" }

func maybeFlush(w Writer) {
    if f, ok := w.(Flusher); ok { f.Flush() }
}

func main() {
    bw := &BufferedWriter{}
    bw.Write("hello")
    maybeFlush(bw)
}

Nil Interface Assertion

Asserting on a nil interface panics. Always ensure the interface is non-nil before asserting:

package main
import "fmt"

func safePrint(i interface{}) {
    if i == nil {
        fmt.Println("nil")
        return
    }
    fmt.Printf("%T: %v\n", i, i)
}

func main() {
    safePrint(nil)
    safePrint(42)
}

reflect.TypeOf Alternative

For printing the type without asserting, use fmt.Sprintf("%T", v) or reflect.TypeOf(v):

package main
import ("fmt"; "reflect")

func main() {
    v := []int{1, 2, 3}
    fmt.Printf("%T\n", v)             // []int
    fmt.Println(reflect.TypeOf(v))    // []int
}

Type Assertion vs Conversion

Type assertion: extract the concrete type from an interface. Type conversion: change one concrete type to another compatible type. They are different operations:

package main
import "fmt"

func main() {
    var i interface{} = int32(5)
    n := i.(int32)          // assertion — OK
    big := int64(n)         // conversion — OK
    fmt.Println(n, big)
}

Comma-ok in select

The comma-ok pattern also works on channel receives to detect a closed channel. The same concise idiom is used consistently in Go.

When to Use Type Switches

Common use cases:

  • JSON unmarshaling with interface{} fields
  • Error categorization
  • Protocol message dispatching
  • Optional interface checking (Flusher, Closer, etc.)

Quick Check

What is the result of a failing non-safe type assertion?

Recap

Key takeaways:

  • x.(T) panics on wrong type; x, ok := x.(T) is safe
  • Type switches handle multiple types cleanly
  • Assert to interfaces to check optional capabilities
  • Never assert on a nil interface

Practice Prompt

Write a function sum(values []any) float64 that uses a type switch to handle int, float64, and string (parse the string) values, skipping others.

Frequently asked questions

Is the “Type Assertions and Type Switches” lesson free?

Yes — the full text of “Type Assertions and Type Switches” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Type Assertions and Type Switches”?

Safe type assertions and switch patterns You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Type Assertions and Type Switches” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining and Implementing Interfaces
  2. Core Standard Library Interfaces
  3. Type Assertions and Type Switches
  4. Interface Composition and Best Practices
← Back to Go Academy