The short answer is No. We cannot achieve method overloading in Golang, at least not in a conventional sense.
Go language doesn’t have classes and objects, but methods in Golang can be used to achieve a version of method overloading. We are talking about methods and not functions, as these two are different concepts in Java.
Let’s see how we can use methods to achieve a version of method overloading. As we know, methods have a receiver type within their definitions, and the receiver type values are used to call a method.
Now, let’s try to calculate the area of a circle, a square, and a rectangle using the Area() method.
Calculate the Area of different shapes
First, we will be creating different structs for different shapes.
type Circle struct {
radius float64
}
type Square struct {
side float64
}
type Rectangle struct {
length float64
width float64
}
Now, we will make method Area for each of the struct types.
func (circle Circle) Area() float64 {
return (3.14) * circle.radius * circle.radius
}
func (square Square) Area() float64 {
return square.side * square.side
}
func (rectangle Rectangle) Area() float64 {
return rectangle.length * rectangle.width
}
We can see that the method for all types is Area() with the same number of arguments and the same return type.
Below is our whole program to calculate the area of each shape.
package main
import "fmt"
type Circle struct {
radius float64
}
type Square struct {
side float64
}
type Rectangle struct {
length float64
width float64
}
func (circle Circle) Area() float64 {
return (3.14) * circle.radius * circle.radius
}
func (square Square) Area() float64 {
return square.side * square.side
}
func (rectangle Rectangle) Area() float64 {
return rectangle.length * rectangle.width
}
func main() {
circle := Circle{radius: 4}
square := Square{side: 5}
rectangle := Rectangle{length: 3, width: 4}
fmt.Println("Area of circle:", circle.Area())
fmt.Println("Area of sqaure:", square.Area())
fmt.Println("Area of rectangle:", rectangle.Area())
}
Output –
Area of circle: 50.24
Area of sqaure: 25
Area of rectangle: 12
In this way, we can achieve functionality similar to method overloading in other programming languages.
If you want to know about methods in go language, we suggest you read this article.
We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.