In Go language, it is allowed to create two or more methods with the same name in the same package, but the receiver of these methods must be of different types. This feature does not available in Go function, means you are not allowed to create same name methods in the same package, if you try to do, then the compiler will throw an error.
Syntax:
func(reciver_name_1 Type) method_name(parameter_list)(return_type){
// Code
}
func(reciver_name_2 Type) method_name(parameter_list)(return_type){
// Code
}
Let us discuss this concept with the help of the examples:
Example 1:
package main
import "fmt"
type student struct {
name string
branch string
}
type teacher struct {
language string
marks int
}
func (s student) show() {
fmt.Println( "Name of the Student:" , s.name)
fmt.Println( "Branch: " , s.branch)
}
func (t teacher) show() {
fmt.Println( "Language:" , t.language)
fmt.Println( "Student Marks: " , t.marks)
}
func main() {
val1 := student{ "Rohit" , "EEE" }
val2 := teacher{ "Java" , 50}
val1.show()
val2.show()
}
|
Output:
Name of the Student: Rohit
Branch: EEE
Language: Java
Student Marks: 50
Explanation: In the above example, we have two same name methods, i.e, show() but with different type of receivers. Here first show() method contain s receiver which is of the student type and the second show() method contains t receiver which is of the teacher type. And in the main() function, we call both the methods with the help of their respective structure variables. If you try to create this show() methods with the same type of receiver, then the compiler throws an error.
Example 2:
package main
import "fmt"
type value_1 string
type value_2 int
func (a value_1) display() value_1 {
return a + "forGeeks"
}
func (p value_2) display() value_2 {
return p + 298
}
func main() {
res1 := value_1( "Geeks" )
res2 := value_2(234)
fmt.Println( "Result 1: " , res1.display())
fmt.Println( "Result 2: " , res2.display())
}
|
Output:
Result 1: GeeksforGeeks
Result 2: 532
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
26 Aug, 2019
Like Article
Save Article