Go Type Assertions

https‮/:‬/www.theitroad.com

Type assertion is a way to extract the underlying value of an interface variable of an interface type, or to check whether the underlying value of an interface variable of an interface type is of a certain type.

In Go, the syntax for type assertion is as follows:

value, ok := interfaceVariable.(Type)

where interfaceVariable is the interface variable, Type is the underlying type that we want to extract, value is a variable of Type, and ok is a boolean variable that is true if the assertion is successful, and false otherwise.

Here's an example of how to use type assertion in Go:

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

    // Extract the underlying value of type string
    s, ok := i.(string)
    if ok {
        fmt.Println(s)
    }

    // Extract the underlying value of type int
    _, ok = i.(int)
    if !ok {
        fmt.Println("Not an integer")
    }
}

In this example, we declare an interface variable i and initialize it with a string value. We then use type assertion to extract the underlying string value from the interface variable, and print it to the console. We also use type assertion to check whether the underlying value is of type int, which is not the case, so we print a message to the console.

Type assertion can also be used with switch statement in Go. Here's an example:

func printType(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Println("Type: int")
    case string:
        fmt.Println("Type: string")
    default:
        fmt.Println("Unknown type")
    }
}

func main() {
    printType(42)
    printType("hello")
    printType(3.14)
}

In this example, we define a function printType that takes an interface variable as its argument, and uses a switch statement with type assertion to determine the underlying type of the interface variable. We then print the type to the console. We call the function with different types of values to demonstrate how the switch statement works.