Golang permite crear dos o más métodos con el mismo nombre en el mismo paquete, pero los receptores de estos métodos deben ser de diferentes tipos. Esta característica no está disponible en las funciones Go, lo que significa que no está permitido crear métodos con el mismo nombre en el mismo paquete. Si intenta hacerlo, el compilador le dará un error.

Sintaxis:
func(reciver_name_1 Type) method_name(parameter_list)(return_type){
// Code
}
func(reciver_name_2 Type) method_name(parameter_list)(return_type){
// Code
}
Veamos el siguiente ejemplo para comprender mejor los métodos con el mismo nombre en Golang:
Ejemplo 1:
// Chương trình Go minh họa cách
// tạo các phương thức cùng tên
package main
import "fmt"
// Tạo các cấu trúc
type student struct {
name string
branch string
}
type teacher struct {
language string
marks int
}
// Các phương thức cùng tên nhưng với
// kiểu receiver khác nhau
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)
}
// Hàm chính
func main() {
// Khởi tạo các giá trị
// of the structures
val1 := student{"Rohit", "EEE"}
val2 := teacher{"Java", 50}
// Gọi các phương thức
val1.show()
val2.show()
}
Resultado:
Name of the Student: Rohit
Branch: EEE
Language: Java
Student Marks: 50
Explicación: En el ejemplo anterior, tenemos dos métodos con el mismo nombre, es decir, show() pero con diferentes tipos de recepción. Aquí, el primer método show() contiene s de tipo estudiante y el segundo método show() contiene t de tipo profesor . Y en la función main() , llamamos a ambos métodos con la ayuda de sus respectivas variables de estructura. Si intenta crear estos métodos show() con el mismo tipo de receptor, el compilador generará un error.
Ejemplo 2:
// Chương trình Go minh họa cách
// tạo các phương thức cùng tên
// với receiver không phải struct
package main
import "fmt"
type value_1 string
type value_2 int
// Tạo hàm cùng tên với
// các kiểu receiver không phải struct khác nhau
func (a value_1) display() value_1 {
return a + "forGeeks"
}
func (p value_2) display() value_2 {
return p + 298
}
// Hàm chính
func main() {
// Khởi tạo giá trị này
res1 := value_1("Geeks")
res2 := value_2(234)
// Hiện kết quả
fmt.Println("Result 1: ", res1.display())
fmt.Println("Result 2: ", res2.display())
}
Resultado:
Result 1: GeeksforGeeks
Result 2: 532