Methods With Same Name in Golang


Go programming language allows multiple methods with the same name, as long as they are defined on different types. This feature is known as method overloading. In this article, we will discuss how to implement methods with the same name in Go and their usage.

What are Methods in Golang?

Methods in Go are functions that are associated with a specific type. They allow us to define behavior for a particular type. Methods can be defined on both user-defined types and built-in types.

Syntax of Methods in Go

func (t Type) methodName(parameterList) (returnType) {
   // Method body
}

Here, t is the receiver type, which can be a struct type or any other user-defined type. The methodName is the name of the method, which can be any valid identifier. The parameterList specifies the method parameters, and the returnType specifies the return type of the method.

Methods with the Same Name in Golang

In Go, it is possible to define multiple methods with the same name, as long as they are defined on different types. This is known as method overloading.

Example

Let's take an example of two methods with the same name −

package main

import (
   "fmt"
   "math"
)

type Rectangle struct {
   length float64
   width  float64
}

func (r Rectangle) Area() float64 {
   return r.length * r.width
}

type Circle struct {
   radius float64
}

func (c Circle) Area() float64 {
   return math.Pi * c.radius * c.radius
}

func main() {
   r := Rectangle{length: 5, width: 3}
   fmt.Println("Rectangle Area:", r.Area())

   c := Circle{radius: 5}
   fmt.Println("Circle Area:", c.Area())
}

Here, we have two methods with the same name Area(). The first Area() method is defined on the Rectangle struct, which calculates the area of a rectangle. The second Area() method is defined on the Circle struct, which calculates the area of a circle.

Output

Rectangle Area: 15
Circle Area: 78.53981633974483

As we can see, even though we have two methods with the same name, Go is able to differentiate between them based on the receiver type.

Conclusion

In conclusion, Go programming language allows defining multiple methods with the same name as long as they are defined on different types. This feature is known as method overloading. In this article, we discussed the syntax of methods in Go, and provided an example of methods with the same name. We hope this article has helped you understand how to implement methods with the same name in Go and their usage.

Updated on: 25-Apr-2023

530 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements