0
0
GoConceptBeginner · 3 min read

What is Type Assertion in Go: Explanation and Examples

In Go, type assertion is a way to extract the concrete value of an interface variable by specifying its actual type. It lets you convert an interface value back to its original type safely or unsafely depending on usage.
⚙️

How It Works

Imagine you have a box labeled "interface" that can hold any item, but you don't know exactly what is inside. Type assertion is like checking the label on the item inside the box to see if it matches a specific type you expect. If it does, you can take it out and use it as that type.

In Go, interfaces can hold values of any type. Type assertion lets you ask the interface, "Are you holding a value of this specific type?" If yes, you get the value in that type. If no, you can handle the error or failure gracefully.

💻

Example

This example shows how to use type assertion to get the original type from an interface value.

go
package main

import "fmt"

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

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

    // Assert that i holds 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
🎯

When to Use

Use type assertion when you have a value stored as an interface and you need to work with its original type. This is common when dealing with functions that accept or return interface{} types, such as in generic containers, JSON decoding, or plugin systems.

For example, if you receive data as an interface but want to perform string operations, you assert it to a string. Always check the assertion result to avoid runtime panics.

Key Points

  • Type assertion extracts the concrete value from an interface.
  • Use the syntax value, ok := interfaceValue.(Type) to safely assert.
  • If the assertion fails, ok is false and no panic occurs.
  • Unsafe assertion value := interfaceValue.(Type) panics if the type does not match.
  • Commonly used when working with interface{} types to recover original data.

Key Takeaways

Type assertion lets you get the original type from an interface value in Go.
Always use the two-value form to safely check if the assertion succeeded.
Type assertion is useful when working with generic or unknown types stored as interfaces.
Unsafe assertions can cause runtime panics if the type does not match.
It helps convert interface{} back to a concrete type for specific operations.