Język Go pozwala na tworzenie dwóch lub więcej metod o tej samej nazwie w tym samym pakiecie, ale odbiorcy tych metod muszą być różnych typów. Funkcja ta nie jest dostępna w funkcjach języka Go, co oznacza, że nie można tworzyć metod o tej samej nazwie w tym samym pakiecie. W takim przypadku kompilator zgłosi błąd.

Składnia:
func(reciver_name_1 Type) method_name(parameter_list)(return_type){
// Code
}
func(reciver_name_2 Type) method_name(parameter_list)(return_type){
// Code
}
Przyjrzyjmy się poniższemu przykładowi, aby lepiej zrozumieć metody o tej samej nazwie w języku Go:
Przykład 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()
}
Wynik:
Name of the Student: Rohit
Branch: EEE
Language: Java
Student Marks: 50
Wyjaśnienie: W powyższym przykładzie mamy dwie metody o tej samej nazwie, tj. show() , ale z różnymi typami odbioru. Tutaj pierwsza metoda show() zawiera s typu student , a druga metoda show() zawiera t typu teacher . W funkcji main() wywołujemy obie metody za pomocą ich odpowiednich zmiennych strukturalnych. Jeśli spróbujesz utworzyć te metody show() z tym samym typem odbiornika, kompilator zgłosi błąd.
Przykład 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())
}
Wynik:
Result 1: GeeksforGeeks
Result 2: 532