Junior — Middle
Explain the concept of type sum in Go language and its usage.
sobes.tech AI
Answer from AI
In the Go language, the concept of sum types is implemented through interfaces and allows for describing variables that can take values from a set of different types, unified by a common interface.
A sum type is a way to express that a value can be one of several types, which is useful for handling different data variants in one place.
Example of usage:
package main
import "fmt"
// Define an interface that unites different types
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func printArea(s Shape) {
fmt.Println("Area:", s.Area())
}
func main() {
var s Shape
s = Circle{Radius: 5}
printArea(s)
s = Rectangle{Width: 3, Height: 4}
printArea(s)
}
Here, the Shape interface acts as a sum type for Circle and Rectangle. This allows functions to accept different types unified by shared behavior.