There is no traditional polymorphism in Go, but you can use interfaces and reflection to achieve similar effects: define the interface and clarify the method set. Create multiple types that implement this interface. Use reflection to call methods dynamically without knowing the specific type.
Implementing polymorphism in Go
How to implement it?
There is no polymorphism in the traditional sense in Go, but you can use interfaces and reflection mechanisms to achieve polymorphic-like behavior.
Interface:
Reflection:
Implementation steps:
Example:
<code class="go">type Shape interface { Area() float64 } type Square struct { side float64 } func (s *Square) Area() float64 { return s.side * s.side } type Circle struct { radius float64 } func (c *Circle) Area() float64 { return math.Pi * c.radius * c.radius } func main() { shapes := []Shape{ &Square{side: 5}, &Circle{radius: 5}, } for _, s := range shapes { fmt.Println("Area:", reflect.ValueOf(s).MethodByName("Area").Call([]reflect.Value{})[0].Float()) } }</code>
Advantages:
Disadvantages:
The above is the detailed content of How to implement polymorphism in golang. For more information, please follow other related articles on the PHP Chinese website!