Junior — Middle
Kuidas implementida tüübi summa (type sum) Go keeles?
sobes.tech AI
Vastus AI-lt
In Go, there is no direct support for type sums (type sum), as in some functional languages (Haskell, Scala). However, a similar effect can be achieved using interfaces and type switch.
An interface in Go describes a set of methods, and any type that implements these methods satisfies the interface. To implement type sums, you can define an interface without methods (empty interface interface{}) or with common methods, and then use a type switch to determine the specific type at runtime.
Example:
package main
import "fmt"
type Shape interface{} // empty interface, can be any type
func area(s Shape) float64 {
switch v := s.(type) {
case Circle:
return 3.14 * v.Radius * v.Radius
case Rectangle:
return v.Width * v.Height
default:
return 0
}
}
type Circle struct {
Radius float64
}
type Rectangle struct {
Width, Height float64
}
func main() {
c := Circle{Radius: 5}
r := Rectangle{Width: 3, Height: 4}
fmt.Println(area(c)) // 78.5
fmt.Println(area(r)) // 12
}
This way, interfaces and type switch allow implementing behavior similar to a type sum, where a variable can take values of different types, and the corresponding logic is executed depending on the type.