Sobes.tech
Junior — Middle

What is the main role of the Union primitive and in what situations is it used?

sobes.tech AI

Answer from AI

Go does not have a primitive union type, but similar functionality is achieved through interfaces and type switches. The main idea of a union is to store a value of one of several types in a single variable. In languages with union types (like C), this saves memory and allows working with different data types in one place.

In Go, interfaces such as interface{} are used for this purpose, and then type assertion or type switch is used to determine the specific type at runtime.

Example of using an interface to mimic a union:

func process(value interface{}) {
    switch v := value.(type) {
    case int:
        fmt.Println("int value", v)
    case string:
        fmt.Println("string value", v)
    default:
        fmt.Println("unknown type")
    }
}

This is used when you need to handle data of different types in one function or structure, for example, when parsing JSON with different possible value types.

What is the main role of the Union primitive and in… - sobes.tech