Methods With Same Name in Golang
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:
// Go program to illustrate how to // create methods of the same name package main import "fmt" // Creating structures type student struct { name string branch string } type teacher struct { language string marks int } // Same name methods, but with // different type of receivers 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) } // Main function func main() { // Initializing values // of the structures val1 := student{ "Rohit" , "EEE" } val2 := teacher{ "Java" , 50} // Calling the methods 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:
// Go program to illustrate how to // create the same name methods // with non-struct type receivers package main import "fmt" type value_1 string type value_2 int // Creating same name function with // different types of non-struct receivers func (a value_1) display() value_1 { return a + "forBeginner" } func (p value_2) display() value_2 { return p + 298 } // Main function func main() { // Initializing the values res1 := value_1( "Beginner" ) res2 := value_2(234) // Display the results fmt.Println( "Result 1: " , res1.display()) fmt.Println( "Result 2: " , res2.display()) } |
Output:
Result 1: w3wiki Result 2: 532