Golang consente di creare due o più metodi con lo stesso nome nello stesso pacchetto, ma i destinatari di questi metodi devono essere di tipo diverso. Questa funzionalità non è disponibile nelle funzioni Go, il che significa che non è consentito creare metodi con lo stesso nome nello stesso pacchetto. Se si tenta di farlo, il compilatore genererà un errore.

Sintassi:
func(reciver_name_1 Type) method_name(parameter_list)(return_type){
// Code
}
func(reciver_name_2 Type) method_name(parameter_list)(return_type){
// Code
}
Diamo un'occhiata al seguente esempio per comprendere meglio i metodi con lo stesso nome in Golang:
Esempio 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()
}
Risultato:
Name of the Student: Rohit
Branch: EEE
Language: Java
Student Marks: 50
Spiegazione: Nell'esempio precedente abbiamo due metodi con lo stesso nome, ovvero show() , ma con tipi di ricezione diversi. Qui, il primo metodo show() contiene s di tipo student e il secondo metodo show() contiene t di tipo teacher . E nella funzione main() chiamiamo entrambi i metodi con l'aiuto delle rispettive variabili di struttura. Se si tenta di creare questi metodi show() con lo stesso tipo di ricevitore, il compilatore genererà un errore.
Esempio 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())
}
Risultato:
Result 1: GeeksforGeeks
Result 2: 532