How to perform type assertions and type switches in Go?

In Go, type assertions and type switches provide a way to work with values of unknown types or interface types.

  1. Type Assertions:

    • A type assertion is a way to extract the underlying value of an interface. It allows you to test whether an interface value holds the specific type you expect and get its value.

    • The basic syntax is: value.(Type), where value is the interface value and Type is the type you expect.

    • Type assertions can return two values: the underlying value of the requested type and a boolean flag indicating whether the assertion is successful or not.

    • Here's an example:

      func printLength(value interface{}) { if str, ok := value.(string); ok { fmt.Println("Length of the string:", len(str)) } else if nums, ok := value.([]int); ok { fmt.Println("Length of the integer slice:", len(nums)) } else { fmt.Println("Unknown type!") } } func main() { printLength("Hello") // Length of the string: 5 printLength([]int{1, 2, 3, 4, 5}) // Length of the integer slice: 5 printLength(42) // Unknown type! }
    • In the above example, printLength function takes an interface value and based on its underlying type, prints its length. It uses type assertions to determine the actual type and perform the required operation.

  2. Type Switches:

    • Type switches are similar to type assertions but allow checking against multiple types in a single switch statement.

    • The basic syntax of a type switch is:

      switch value := myInterface.(type) { case Type1: // Type1-specific logic using value case Type2: // Type2-specific logic using value default: // Default logic when neither Type1, nor Type2 match }
    • The myInterface.(type) construct returns the underlying value along with its type.

    • Here's an example:

      func printType(value interface{}) { switch t := value.(type) { case string: fmt.Println("String:", t) case int: fmt.Println("Int:", t) case bool: fmt.Println("Bool:", t) default: fmt.Println("Unknown type!") } } func main() { printType("Hello") // String: Hello printType(42) // Int: 42 printType(true) // Bool: true printType(3.14159) // Unknown type! }
    • In the above example, printType function takes an interface value and uses a type switch to determine its actual type and performs the required operation accordingly.

Type assertions and type switches are useful when working with interfaces and generic code where the exact type is unknown at compile-time. They allow you to handle different types dynamically and enable more flexible and robust code.