Golang , aynı paket içerisinde aynı isimde iki veya daha fazla metot oluşturulmasına izin verir, ancak bu metotların alıcılarının farklı tiplerde olması gerekir. Bu özellik Go fonksiyonlarında mevcut değildir, yani aynı paket içerisinde aynı isimli metotlar oluşturmanıza izin verilmez, bunu yapmaya çalışırsanız derleyici size hata verecektir.

Sözdizimi:
func(reciver_name_1 Type) method_name(parameter_list)(return_type){
// Code
}
func(reciver_name_2 Type) method_name(parameter_list)(return_type){
// Code
}
Golang'da aynı isimli metotları daha iyi anlamak için aşağıdaki örneğe bakalım:
Örnek 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()
}
Sonuç:
Name of the Student: Rohit
Branch: EEE
Language: Java
Student Marks: 50
Açıklama: Yukarıdaki örnekte aynı adı taşıyan ( show()) ancak farklı alma türlerine sahip iki metodumuz var. Burada, ilk show() metodu öğrenci tipinde s , ikinci show() metodu ise öğretmen tipinde t kişisini içerir . Ve main() fonksiyonunda , her iki metodu da ilgili yapı değişkenlerinin yardımıyla çağırıyoruz. Bu show() metotlarını aynı alıcı türüyle oluşturmaya çalışırsanız derleyici bir hata verecektir.
Örnek 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())
}
Sonuç:
Result 1: GeeksforGeeks
Result 2: 532