Hello! In our lesson today, we’re delving into polymorphism in Go. Polymorphism provides the ability for different types to be accessed through the same interface. This enables a single function to operate on multiple types. In Go, interfaces facilitate polymorphism by allowing various types to share behaviors without relying on a traditional class hierarchy. Let's explore how Go's type system provides this flexibility.
In Go, polymorphism is achieved through the use of interfaces. Interfaces specify a set of methods that different types can implement, thereby allowing these types to be manipulated consistently. Consider a graphical shape interface; whether the shape is a rectangle or a circle, the operations (such as calculating the area) may differ. Let’s illustrate how polymorphism functions in Go with an example using shapes.
Go1package main 2 3import ( 4 "fmt" 5 "math" 6) 7 8// Shape interface specifies a method for calculating the area 9type Shape interface { 10 Area() float64 11} 12 13type Rectangle struct { 14 length, width float64 15} 16 17func (r Rectangle) Area() float64 { 18 return r.length * r.width 19} 20 21type Circle struct { 22 radius float64 23} 24 25func (c Circle) Area() float64 { 26 return math.Pi * c.radius * c.radius 27} 28 29// PrintArea function takes a Shape as a parameter and displays its area 30func PrintArea(s Shape) { 31 fmt.Println(s.Area()) 32} 33 34func main() { 35 var shape Shape 36 37 shape = Rectangle{length: 2, width: 3} 38 PrintArea(shape) // Prints: 6.0 39 40 shape = Circle{radius: 5} 41 PrintArea(shape) // Prints: 78.53981633974483 42}
In this example, the Shape
interface defines an Area()
method. Both the Rectangle
and Circle
structs implement this method, allowing them to be treated as a Shape
. Polymorphism enables the Area()
method to function differently depending on whether the shape is a rectangle or a circle.
The PrintArea
function takes a Shape
interface as its parameter, meaning it accepts any struct that implements the Area()
method defined in the Shape
interface. If a struct does not implement the Area()
method, it cannot be passed to PrintArea
, as it does not satisfy the requirements of the Shape
interface.
Great job! You've learned about polymorphism in Go, implemented through interfaces. By using interfaces, different types can adopt shared behaviors without the need for class hierarchies. Now, take the next step and enhance your Go programs by applying these concepts in practice. Happy coding with Go’s robust approach to polymorphism!