what is polymorphism
tags: learning software programming go
content
Note
- the word polymorphism means “many forms or shapes”
- we can think of it as: the underlying data object could have many shapes
Go interface is a good example:
type Animal interface {
MakeNoise() string
}
type Cat struct {
Name string
Breed string
}
func (c Cat) MakeNoise() string {
return "meow"
}
type Fish struct {
Name string
Tail string
}
func (f Fish) MakeNoise() string {
return "blueb"
}
// other code
func (z Zoo) WatchAminal (pet Animal) {
animal.MakeNoise()
}CatandFishboth implementMakeNoisemethod, so they implementsAnimalinterface implicitly- But they are different data structures or different objects:
- one has
Breed, the other hasTail
- one has
- For the caller
WatchAnimal- it doesn’t care about what the underlying data structure for
petis - it only cares if
petcanMakeNoise
- it doesn’t care about what the underlying data structure for
- this is polymorphism!
- the word polymorphism means many forms/shapes
- in this case, we are using the same code to handle different objects!
- the interface
Animalhas many forms/shapes
When we don’t need polymorphism:
type Agent struct {
prompt string
tools *tool.Tools
hooks *EventHooks
maxIterations int
}
func (a *Agent) NewMainAgent() {
tools
}
type SubAgent struct {...}
func (a *SubAgent) SystemPrompt() string {...}
func (a *SubAgent) GetTools() []Tool {...}
func (a *SubAgent) GetMaxTurn() int {...}