Sobes.tech
Middle

How is polymorphism implemented in the Go programming language?

sobes.tech AI

Answer from AI

Polymorphism in Go is implemented through interfaces.

An interface defines a set of method signatures. A type implements an interface if it has all the methods defined in the interface with matching signatures. Implementation does not require explicit declaration (implements as in Java).

Example:

// Shape - interface defining the Area() method
type Shape interface {
	Area() float64
}

// Circle - struct implementing the Shape interface
type Circle struct {
	radius float64
}

// Area - method for Circle
func (c Circle) Area() float64 {
	return 3.14 * c.radius * c.radius
}

// Rectangle - struct implementing the Shape interface
type Rectangle struct {
	width, height float64
}

// Area - method for Rectangle
func (r Rectangle) Area() float64 {
	return r.width * r.height
}

// Function accepting the Shape interface
func printArea(s Shape) {
	fmt.Println("Area:", s.Area())
}

// is invoked with different concrete types
func main() {
	circle := Circle{radius: 5}
	rectangle := Rectangle{width: 10, height: 5}

	printArea(circle)    // Outputs: Area: 78.5
	printArea(rectangle) // Outputs: Area: 50

	// Using a slice of interfaces
	shapes := []Shape{circle, rectangle}
	for _, shape := range shapes {
		printArea(shape)
	}
}

Main aspects:

  • Interfaces: Define behavior.
  • Implicit implementation: A type automatically implements an interface if it matches its signatures.
  • Duck typing (similar to): "If it quacks like a duck and walks like a duck, then it is a duck." Behavior is determined by the type.
  • Polymorphic functions: Functions can accept interface types as arguments, working with any type that implements the interface.
  • Built-in polymorphism: Basic form of polymorphism also manifests in functions working with different data types (e.g., built-in functions len, cap, append work with various collections).
  • Embedding: Allows implementing "composition instead of inheritance," but can also be used to create types that "inherit" methods from other types, somewhat resembling polymorphism.

Polymorphism in Go is ad-hoc, based on structural typing via interfaces. This differs from classical subtyping polymorphism found in languages with explicit inheritance.