Type assert in golang and type assert with switch case

In Go, type assertion is a way to check and extract the underlying value of an interface. It allows you to determine whether the underlying concrete type of an interface is of a specific type and, if so, obtain its value. Here’s an example of type assertion in Go:

The syntax for a type assertion is:

value, ok := x.(T)

where x is an expression of an interface type, T is a type, and ok is a boolean that is true if the assertion holds, and false otherwise.

Here’s a simple example:

package main

import "fmt"

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

    // Type assertion to extract int value
    value, ok := i.(int)
    if ok {
        fmt.Println("Asserted value:", value)
    } else {
        fmt.Println("Type assertion failed")
    }

    // Type assertion to extract string value (fails since the underlying type is int)
    stringValue, ok := i.(string)
    if ok {
        fmt.Println("Asserted string value:", stringValue)
    } else {
        fmt.Println("Type assertion for string failed")
    }
}

In this example:

  • We have an interface i that holds the value 42.
  • We use a type assertion to try to extract an int from the interface. Since the underlying type is int, the assertion succeeds, and we print the value.
  • We also attempt to assert the interface to a string, which fails because the underlying type is not a string.

It’s important to check the boolean value (ok) returned by the type assertion to ensure that the assertion succeeded. If the assertion fails, the variable value will be the zero value of type T, and the program may panic.

Here’s another example with type switch, which is often used when dealing with interfaces of unknown types:

func processInterface(i interface{}) {
    switch value := i.(type) {
    case int:
        fmt.Println("Value is an int:", value)
    case string:
        fmt.Println("Value is a string:", value)
    default:
        fmt.Println("Unknown type")
    }
}

In this example, the type keyword in the switch statement is used to perform a type switch, allowing different cases for different types.

Leave a Reply

Your email address will not be published. Required fields are marked *