CodeNebula
Go🔧Core Languagebeginner

Type Assertions

Go · Core Language · Run with go run

Explanation

A type assertion extracts the concrete value stored inside an interface. `v, ok := i.(T)` is the safe two-value form — `ok` is `false` instead of panicking when the assertion fails. The single-value form `v := i.(T)` panics on mismatch, so reserve it for cases where the type is guaranteed.

Real-World Scenario

A function accepts `error` and wants special handling for a specific error type. A type assertion `if ne, ok := err.(*net.OpError); ok` checks whether the error is a network operation error and, if so, reads its fields.

Quick Snippet

snippet.go
var i any = "hello"

// Safe form — never panics
s, ok := i.(string)
fmt.Println(s, ok) // hello true

n, ok := i.(int)
fmt.Println(n, ok) // 0 false

// Unsafe form — panics if i does not hold a string
s = i.(string)

Full Example

type_assertions.go
// Compile: go run type_assertions.go
// Output:
//   string value: hello (ok=true)
//   int assertion ok: false
//   recovered from a failed assertion
package main

import "fmt"

func main() {
	var i any = "hello"

	// Safe two-value form — never panics
	s, ok := i.(string)
	fmt.Printf("string value: %s (ok=%t)\n", s, ok)

	_, ok = i.(int)
	fmt.Printf("int assertion ok: %t\n", ok)

	// Single-value form panics on mismatch — recover to keep running
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("recovered from a failed assertion")
		}
	}()
	_ = i.(int) // panics: interface conversion
}
Run command
go run type_assertions.go