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

Type Assertions

A type assertion is you telling Go 'trust me, I know what's really inside this generic box' -- and Go checks whether you're right.

The Two-Value Form

v, ok := i.(Type) attempts to extract the concrete value as the given type, setting ok to true on success or false (with v as the zero value) on failure -- this never panics, making it the safe default.

Note: Prefer the two-value form whenever the type isn't already guaranteed.

Example: The Two-Value Form

markup
package main

import "fmt"

func main() {
	var i interface{} = "hello"
	s, ok := i.(string)
	fmt.Println(s, ok)

	n, ok := i.(int)
	fmt.Println(n, ok)
}

The Single-Value Form

i.(Type) without the ok flag returns just the value, but panics immediately if the interface doesn't actually hold that type -- useful when a mismatch would genuinely be a programmer error.

Note: Only use this form when you are certain of the underlying type, or you've already checked with a type switch.

Example: The Single-Value Form

markup
package main

import "fmt"

func main() {
	var i interface{} = 42
	n := i.(int) // safe here, we know it's an int
	fmt.Println(n + 8)
}

Asserting to an Interface Type

A type assertion can also check whether a value satisfies a different, narrower interface than the one it's currently stored as, which is common when working with a general interface{} that might optionally support extra behavior.

Example: Asserting to an Interface Type

markup
package main

import "fmt"

type Speaker interface {
	Speak() string
}

type Dog struct{}

func (Dog) Speak() string { return "Woof" }

func main() {
	var i interface{} = Dog{}
	if s, ok := i.(Speaker); ok {
		fmt.Println(s.Speak())
	}
}
Common Mistakes
  1. Using the single-value form (v := i.(Type)) without the ok flag, which panics at runtime if the assertion is wrong.
  2. Assuming a type assertion converts a value, when it's actually just checking/extracting the concrete type already stored inside the interface.
  3. Asserting to the wrong concrete type when a pointer versus value receiver distinction matters (e.g. *T vs T stored in the interface).
Chapter Summary
  • A type assertion, i.(Type), extracts the concrete value stored in an interface value.
  • The single-value form panics if the assertion fails -- use it only when you're certain of the type.
  • The two-value form, v, ok := i.(Type), returns false instead of panicking on a mismatch.
  • Type assertions are how you get back a concrete type after storing it in an interface{} or other interface.
🔒

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.