Compile Time Polymorphism in Go

Compile Time Polymorphism in Go

In this tutorial, we will discuss compile time polymorphism in Go language. In compile time polymorphism, the call is resolved during compile time by the compiler. Some of the forms for compile-time polymorphism are

  • Method/Function Overloading: More than one method/function exists with the same name but with different signatures or possibly different return types
  • Operator Overloading: The Same operator is used for operating on different data types
Compile Time Polymorphism in Go

Go language doesn’t support Method Overloading. For example, see the below program demonstrating that go doesn’t support method overloading.

package main

type maths struct{}

func (m *maths) add(a, b int) int {
	return a + b
}

func (m *maths) add(a, b, c int) int {
	return a + b + c
}

func main() {
	m := &maths{}
}

Output

./prog.go:9:6: method redeclared: maths.add
	method(*maths) func(int, int) int
	method(*maths) func(int, int, int) int
./prog.go:9:17: (*maths).add redeclared in this block
	prog.go:5:6: previous declaration

Run in playground

Go language also doesn’t support operator overloading. The reason for this is stated in faq of go – https://golang.org/doc/faq#overloading

Now the question is there any alternative to do method overloading in GO. This is where the Variadic function in go comes into the picture. See below program

package main

import "fmt"

type maths struct{}

func (m *maths) add(numbers ...int) int {
	result := 0
	for _, num := range numbers {
		result += num
	}
	return result
}

func main() {
	m := &maths{}

	fmt.Println("Result is : ", m.add(5, 10))
	fmt.Println("Result is : ", m.add(10, 20, 30))
}

Output

Result is :  15
Result is :  60

Run in playground

Conclusion

Go doesn’t directly support method/function/operator overloading, but variadic function provides a way of achieving the same with increased code complexity.

Compile Time Polymorphism in Go

Scroll to top