Hi,
I am Kamal Hinduja based Geneva, Switzerland(Swiss). Can anyone explain Explain interfaces in Go. How does Go support polymorphism?
Thanks, Regards
Kamal Hinduja Geneva, Switzerland
Hi,
I am Kamal Hinduja based Geneva, Switzerland(Swiss). Can anyone explain Explain interfaces in Go. How does Go support polymorphism?
Thanks, Regards
Kamal Hinduja Geneva, Switzerland
The interface{} is a joker sort of. I use polymorphism in databases and in Go, normally through switch statements and interface{} keeping the code as DRY as possible. While there are other ways to implement polymorphism, it’s often debated - especially in database design.
package main
import "fmt"
func poly(value interface{}) {
switch v := value.(type) {
case int:
fmt.Printf("Integer: %d\n", v)
case string:
fmt.Printf("String: %s\n", v)
default:
fmt.Printf("Unknown type: %T\n", v)
}
}
func main() {
poly(42) // Integer: 42
poly("hello") // String: hello
poly(3.14) // Unknown type: float64
}
For a very simple example of polymorphism through interfaces, check this: Go Playground - The Go Programming Language
Notice how I define an interface first, which describes a behaviour. Then I define a simplistic compute function which works with whatever future implementations of said behaviour.
Only later I define structs which implement the interface. I end up not needing to update the compute function, since it already knows how to work with the new types, since their behaviour is the same / they implement the same interface.
In Go, interfaces define behavior — any type that implements the methods of an interface automatically satisfies it. This is how Go supports polymorphism — different types can be used interchangeably if they share the same interface.