union in go

The union keyword in the Go programming language is used to combine multiple struct types into a single type. It is similar to how a union works in other programming languages. Here are the steps involved in using a union in Go:

  1. Define the struct types: Before using a union, we need to define the individual struct types that we want to combine. Each struct type represents a distinct set of fields.

  2. Create a union type: Next, we create a new struct type to represent the union. This struct type will include all the fields from the individual struct types that we want to combine.

  3. Use the union: Once the union type is defined, we can create variables of that type and access the fields from the individual struct types. The union allows us to store values of different types in the same variable.

  4. Handle field conflicts: If there are fields with the same name in the individual struct types, we need to handle the conflicts. When accessing a field in the union, we need to specify which struct type the field belongs to.

Here's an example to illustrate the usage of union in Go:

// Step 1: Define the struct types
type Rectangle struct {
    width  int
    height int
}

type Circle struct {
    radius int
}

// Step 2: Create a union type
type ShapeUnion struct {
    Rectangle
    Circle
}

func main() {
    // Step 3: Use the union
    var shape ShapeUnion

    shape.Rectangle = Rectangle{width: 10, height: 5}
    fmt.Println("Rectangle width:", shape.Rectangle.width)
    fmt.Println("Rectangle height:", shape.Rectangle.height)

    shape.Circle = Circle{radius: 3}
    fmt.Println("Circle radius:", shape.Circle.radius)

    // Step 4: Handle field conflicts
    shape.Rectangle.width = 15
    fmt.Println("Updated rectangle width:", shape.Rectangle.width)
}

In this example, we define two struct types - Rectangle and Circle. We then create a union type ShapeUnion that includes both Rectangle and Circle. In the main function, we create a variable shape of type ShapeUnion and assign values to its fields. We can access the fields using the dot notation.

Please note that the example code assumes the necessary imports and package declaration are present. It is also important to handle field conflicts correctly when using a union in Go.