How to Simulate Union Type in Golang

Golang does not have a direct representation of a “union” type like in some other programming languages. However, you can simulate union type using “interfaces” and “type assertions”.

An empty interface (interface{}) can be used as a union type because it can hold any value.

You can pass or store multiple types using an empty interface as a function argument or struct field.

You can use type assertions or a switch to get the actual value and its type.

Example

Here’s an example of using an empty interface as a union type.

package main

import "fmt"

func main() {
  // Use the empty interface to store different types in a slice
  unionSlice := []interface{}{21, "golang", 3.14}

  for _, v := range unionSlice {
    switch value := v.(type) {
      case int:
        fmt.Println("Integer value:", value)
      case string:
        fmt.Println("String value:", value)
      case float64:
        fmt.Println("Float64 value:", value)
      default:
        fmt.Println("Unknown type")
    }
  }
}

Output

Integer value: 21
String value: golang
Float64 value: 3.14

In this example, we used an empty interface to create a slice (unionSlice) that can store different types of values (int, string, and float64).

In the next step, we iterated through the slice and used a type switch to determine the actual type of each value and process it accordingly.

While this approach provides flexibility, it can also lead to runtime errors if you don’t handle all possible types or make a mistake in the type assertions.

Additionally, an empty interface can make your code less type-safe and less self-documenting, so you should use it judiciously and consider alternatives like custom types, structs, or interfaces with defined methods when appropriate.

Leave a Comment