0
0
GoHow-ToBeginner · 3 min read

How to Use Type Assertion in Go: Simple Guide with Examples

In Go, use value.(Type) to assert that an interface value holds a specific concrete type. This lets you access the underlying value with that type safely or check if the assertion succeeded.
📐

Syntax

The basic syntax for type assertion is value.(Type), where value is an interface variable and Type is the concrete type you expect.

You can use two forms:

  • v := value.(Type) - asserts and returns the value as Type, panics if wrong.
  • v, ok := value.(Type) - asserts and returns value and a boolean ok indicating success.
go
var i interface{} = "hello"

// Assert i holds a string
s := i.(string)

// Assert with check
s, ok := i.(string)
if ok {
    // use s
}
💻

Example

This example shows how to use type assertion to get the concrete type from an interface and handle failure safely.

go
package main

import "fmt"

func main() {
    var i interface{} = "hello"

    // Assert i is a string
    s, ok := i.(string)
    if ok {
        fmt.Println("String value:", s)
    } else {
        fmt.Println("Not a string")
    }

    // Assert i is an int
    n, ok := i.(int)
    if ok {
        fmt.Println("Int value:", n)
    } else {
        fmt.Println("Not an int")
    }
}
Output
String value: hello Not an int
⚠️

Common Pitfalls

Common mistakes include:

  • Using value.(Type) without the ok check, which causes a panic if the type is wrong.
  • Asserting to the wrong type accidentally.
  • Forgetting that type assertion only works on interface types.

Always use the two-value form if unsure about the type.

go
package main

import "fmt"

func main() {
    var i interface{} = 10

    // This will panic if i is not a string
    // s := i.(string) // Uncommenting causes panic

    // Safe way
    s, ok := i.(string)
    if ok {
        fmt.Println("String:", s)
    } else {
        fmt.Println("Not a string, safe check")
    }
}
Output
Not a string, safe check
📊

Quick Reference

UsageDescription
v := value.(Type)Assert interface holds Type, panics if not
v, ok := value.(Type)Assert interface holds Type, ok is true if yes
Only works on interface typesCannot assert on non-interface variables
Use ok form to avoid panicPrevents runtime crashes on wrong type

Key Takeaways

Use value.(Type) to extract the concrete type from an interface in Go.
Always prefer the two-value form v, ok := value.(Type) to safely check the type.
Type assertion panics if you assert the wrong type without checking.
Type assertion only works on variables of interface type.
Use type assertion to access underlying values stored in interfaces.