English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statements

Golang functions & methods

Golang structs

Golang slices & arrays

Golang strings(String)

Golang pointers

Golang interfaces

Golang concurrency

Golang exceptions(Error)

Other Golang items

Go Same Name Method

In Go language, it is allowed to create two or more methods with the same name in the same package, but these methods must have different receiversmust have different typesThis feature is not available in Go functions, which means it is not allowed to create methods with the same name in the same package. If you try to do so, the compiler will throw an error.

Syntax:

func(receiver_name_1 Type) method_name(parameter_list)(return_type){
    // Code
}
func(receiver_name_2 Type) method_name(parameter_list)(return_type){
    // Code
}

Let's discuss this concept with an example:

Example1:

package  main 
  
import  "fmt"
  
//Create structure
type  student  struct  { 
    name      string 
    branch  string 
} 
  
type  teacher  struct  { 
    language  string 
    marks      int
} 
  
//Methods with the same name but different receiver types
func  (s  student)  show()  { 
  
    fmt.Println("Student Name:  ",  s.name) 
    fmt.Println("Branch:  ",  s.branch) 
} 
  
func  (t  teacher)  show()  { 
  
    fmt.Println("Language:  ",  t.language) 
    fmt.Println("Student  Marks:  ",  t.marks) 
} 
  
func  main()  { 
  
    // Initialize the value of the structure
    val1 :=  student{"Rohit",  "EEE"} 
  
    val2 :=  teacher{"Java", 50} 
  
    //Call method
    val1.show() 
    val2.show() 
}

Output:

Student Name:  Rohit
Branch:  EEE
Language:  Java
Student  Marks:  50

Usage instructions:In the above example, we have two methods with the same name, namelyshow(),but the receiver types are different. Here, the firstshow()method contains a receiver of type s student, the secondshow()method contains a receiver of type t teacher. Inmain()In the function, we use the respective struct variables to call these two methods. If you try to use the same type receiver to create thisshow()If the compiler throws an error when the same type receiver is created for this method in the function.

Example2:

//Create methods with the same name
//Non-structured type receiver
package  main 
  
import  "fmt"
  
type  value_1 string 
type  value_2 int
  
//Create functions with the same name
//Non-structured receiver of different types
func  (a  value_1)  display()  value_1 { 
  
    return  a + ".com"
} 
  
func  (p  value_2)  display()  value_2 { 
  
    return  p + 298 
} 
  
func  main()  { 
  
    //Initial value 
    res1 :=  value_1("w3codebox) 
    res2 :=  value_2(234) 
  
    // Print display result
    fmt.Println("Result 1:  ",  res1.display()) 
    fmt.Println("Result 2:  ",  res2.display()) 
}

Output:

Result 1:  oldtoolbag.com
Result 2: 532