Go - Type Assertion



The type assertion in Golang is a way to retrieve the dynamic value of an interface. It is used to extract the underlying value of an interface and convert it to a specific type. This is useful when you have an interface with a value of an unknown type and you need to operate on that value.

Following is the syntax to the type assertion in Golang −

t := Value.(TypeName)

Basic Type Assertion

The basic type assertion is a way to inform the compiler about the specific type of a variable when it can't automatically determine it that helps to avoid runtime errors.

Example

In this example, we assert the type of an interface value to a string.

 
package main

import (
    "fmt"
)

func main() {
    var i interface{} = "hello"
    
    // Type assertion to retrieve the string value
    s := i.(string)
    fmt.Println(s)
}

When the above code is compiled and executed, it produces the following result −

hello

Type Assertion with Ok-idiom

The Ok-idiom is a common pattern for handling errors, and it's often used with type assertions to ensure that operations succeed.

Example

In this example, we use the Ok-idiom to check if the type assertion is successful or not to avoid panics.

package main

import (
    "fmt"
)

func main() {
    var i interface{} = "hello"
    
    // Type assertion with Ok-idiom
    if s, ok := i.(string); ok {
        fmt.Println("String value:", s)
    } else {
        fmt.Println("Not a string")
    }
}

When the above code is compiled and executed, it produces the following result −

String value: hello

Handling Failed Type Assertion

Handling a failed type assertion involves managing the scenario where a type assertion does not hold, and the program needs to handle the resulting error.

Example

In this example, we will ensure that what happens when the type assertion fails.

package main
import (
    "fmt"
)

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

    // Attempting to assert to a wrong type
    if s, ok := i.(string); ok {
        fmt.Println(s)
    } else {
        fmt.Println("Type assertion failed")
    }
}

When the above code is compiled and executed, it produces the following result −

Type assertion failed
Advertisements